Skip to main content

Session

Struct Session 

Source
pub struct Session { /* private fields */ }
Expand description

A session that interacts with a language model.

A session maintains state between requests, allowing for multi-turn conversations. You can reuse the same session for multiple prompts or create a new one each time.

Dropping a session requests cooperative cancellation. A Rust tool callback that is already queued or running may continue until it returns; its dispatcher-owned callback context remains valid for that duration.

§Example

use fm_rs::{Session, SystemLanguageModel, GenerationOptions};

let model = SystemLanguageModel::new()?;
let session = Session::new(&model)?;

let response = session.respond("Hello!", &GenerationOptions::default())?;
println!("{}", response.content());

Implementations§

Source§

impl Session

Source

pub fn builder<M: LanguageModel + ?Sized>(model: &M) -> SessionBuilder<'_, M>

Creates a session builder for combining instructions, tools, and built-in system tools.

Source

pub fn new<M: LanguageModel + ?Sized>(model: &M) -> Result<Self>

Creates a new session with the given model.

Source

pub fn with_instructions<M: LanguageModel + ?Sized>( model: &M, instructions: &str, ) -> Result<Self>

Creates a new session with instructions.

Instructions define the model’s behavior and role.

Source

pub fn with_tools<M: LanguageModel + ?Sized>( model: &M, tools: &[Arc<dyn Tool>], ) -> Result<Self>

Creates a new session with tools.

Tools allow the model to call external functions during generation.

Source

pub fn with_instructions_and_tools<M: LanguageModel + ?Sized>( model: &M, instructions: &str, tools: &[Arc<dyn Tool>], ) -> Result<Self>

Creates a new session with both instructions and tools.

Source

pub fn from_transcript<M: LanguageModel + ?Sized>( model: &M, transcript_json: &str, ) -> Result<Self>

Creates a session from a transcript JSON string.

This allows restoring a previous conversation. Note: Restored sessions do not have tools - use with_tools for new sessions.

Source

pub fn respond( &self, prompt: &str, options: &GenerationOptions, ) -> Result<Response>

Sends a prompt and waits for the complete response.

This method blocks until the model finishes generating.

Source

pub fn respond_with_reasoning( &self, prompt: &str, options: &GenerationOptions, reasoning_level: ReasoningLevel, ) -> Result<Response>

Sends a prompt with Foundation Models 27 extended reasoning.

Extended reasoning is a Foundation Models 27 ContextOptions request. The framework decides whether the session’s model honors the level; models without the capability report a typed error. On an older build SDK or runtime, this returns Error::UnsupportedPlatform.

Source

pub fn respond_with_reasoning_timeout( &self, prompt: &str, options: &GenerationOptions, reasoning_level: ReasoningLevel, timeout: Duration, ) -> Result<Response>

Sends a prompt with extended reasoning and waits up to timeout.

If timeout is zero, this behaves like respond_with_reasoning. Positive sub-millisecond timeouts are rounded up to one millisecond.

Timeout cancellation is cooperative: the abandoned generation may keep running in the background, in which case new requests report Error::ConcurrentRequests until it finishes, and an already-dispatched tool call may still run (side effects included) after this method has returned Error::Timeout.

Source

pub fn respond_with_timeout( &self, prompt: &str, options: &GenerationOptions, timeout: Duration, ) -> Result<Response>

Sends a prompt and waits for the complete response, with a timeout.

If timeout is zero, this behaves like respond. Positive sub-millisecond timeouts are rounded up to one millisecond.

Timeout cancellation is cooperative: the abandoned generation may keep running in the background, in which case new requests report Error::ConcurrentRequests until it finishes, and an already-dispatched tool call may still run (side effects included) after this method has returned Error::Timeout.

Source

pub fn stream_response<F>( &self, prompt: &str, options: &GenerationOptions, on_chunk: F, ) -> Result<()>
where F: FnMut(&str) + Send,

Sends a prompt and streams the response.

The on_chunk callback is called for each text chunk as it arrives. Chunks are incremental: concatenating every chunk yields the full response. This method blocks until streaming is complete.

§Example
use fm_rs::{Session, SystemLanguageModel, GenerationOptions};

let model = SystemLanguageModel::new()?;
let session = Session::new(&model)?;

session.stream_response("Tell me a story", &GenerationOptions::default(), |chunk| {
    print!("{}", chunk);
})?;
Source

pub fn respond_with_attachments( &self, prompt: &str, attachments: &[Attachment<'_>], options: &GenerationOptions, ) -> Result<Response>

Sends a prompt with image attachments and blocks until the response is ready (Foundation Models 27 multimodal prompting).

The on-device model accepts images for description, extraction, and classification; the framework handles scaling and color conversion. With no attachments this behaves like respond. Requires a 27 build SDK and runtime; otherwise returns Error::UnsupportedPlatform. Models without the image capability report Error::UnsupportedCapability.

Source

pub fn usage(&self) -> Result<SessionUsage>

Returns exact cumulative token usage for this session.

Foundation Models 27 reports authoritative input, cached-input, output, and reasoning token counts across all requests in this session. To measure a single request, snapshot before and after and use SessionUsage::delta_since. Per-response usage is bridged into Response::usage on blocking response paths; per-response usage for streaming remains unsupported. On older build SDKs or runtimes this returns Error::UnsupportedPlatform; use crate::estimate_tokens there instead.

Source

pub fn set_transcript(&self, transcript_json: &str) -> Result<()>

Replaces this session’s transcript (Foundation Models 27).

The JSON must be a Foundation Models Transcript, such as one returned by transcript_json and edited. Fails while the session is responding. On older build SDKs or runtimes this returns Error::UnsupportedPlatform; there, create a new session with Session::from_transcript instead.

Source

pub fn set_transcript_error_handling_policy( &self, policy: Option<TranscriptErrorHandlingPolicy>, ) -> Result<()>

Sets or clears how the transcript is repaired after a failed request (Foundation Models 27).

None restores the framework default. On older build SDKs or runtimes this returns Error::UnsupportedPlatform.

Source

pub fn cancel(&self)

Cancels the in-flight generation (blocking or streaming), if any.

Every generation method blocks the calling thread and Session is not Sync, so this cannot be reached while a request is in flight. To cancel from another thread, obtain a CancellationHandle via cancellation_handle before starting.

Source

pub fn cancellation_handle(&self) -> CancellationHandle

Returns a thread-safe handle that can cancel this session’s in-flight generation from another thread.

The handle holds its own reference to the underlying Swift session, so it remains safe to use (as a no-op) after the Session is dropped. It is session-scoped rather than generation-scoped: cancel targets whichever generation is in flight when it is called. A delayed call intended for an earlier generation can therefore cancel a later one; coordinate its lifetime with the operation it is meant to cancel.

§Example
use fm_rs::{GenerationOptions, Session, SystemLanguageModel};

let model = SystemLanguageModel::new()?;
let session = Session::new(&model)?;
let handle = session.cancellation_handle();

let canceller = std::thread::spawn(move || {
    std::thread::sleep(std::time::Duration::from_millis(100));
    handle.cancel();
});

let result = session.stream_response(
    "Tell me a very long story",
    &GenerationOptions::default(),
    |chunk| print!("{chunk}"),
);
assert!(matches!(result, Err(fm_rs::Error::Cancelled(_))));
canceller.join().expect("canceller thread panicked");
Source

pub fn is_responding(&self) -> bool

Checks if the session is currently generating a response.

Source

pub fn transcript_json(&self) -> Result<String>

Gets the session transcript as a JSON string.

This can be used to persist and restore conversations.

Source

pub fn context_usage(&self, limit: &ContextLimit) -> Result<ContextUsage>

Estimates current context usage based on the session transcript.

Source

pub fn ensure_context_within(&self, limit: &ContextLimit) -> Result<()>

Returns an error if the estimated context usage exceeds the configured limit.

Source

pub fn prewarm(&self, prompt_prefix: Option<&str>) -> Result<()>

Prewarms the model with an optional prompt prefix.

This can reduce latency for the first response.

Source

pub fn respond_json( &self, prompt: &str, schema: &Value, options: &GenerationOptions, ) -> Result<String>

Sends a prompt and returns a structured JSON response.

The schema is a JSON Schema that describes the expected output format. The model is instructed to produce JSON that matches the schema.

§Example
use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
struct Person {
    name: String,
    age: u32,
}

let model = SystemLanguageModel::new()?;
let session = Session::new(&model)?;

let schema = json!({
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer" }
    },
    "required": ["name", "age"]
});

let json_str = session.respond_json(
    "Generate a fictional person",
    &schema,
    &GenerationOptions::default()
)?;

let person: Person = serde_json::from_str(&json_str)?;
Source

pub fn respond_json_with_timeout( &self, prompt: &str, schema: &Value, options: &GenerationOptions, timeout: Duration, ) -> Result<Response>

Sends a prompt and returns a structured JSON response with a timeout.

The response content contains the extracted JSON string. On Foundation Models 27, Response::usage also exposes the framework’s per-response token usage when available. If timeout is zero, this uses the same path as respond_json. Positive sub-millisecond timeouts are rounded up to one millisecond, the finest resolution supported by the Swift bridge.

The timeout bounds only the caller’s wait. On expiry, the bridge requests cooperative task cancellation and returns Error::Timeout; it cannot force Foundation Models framework work to stop immediately. While the abandoned generation drains, new requests report Error::ConcurrentRequests, and an already-dispatched tool call may still run (side effects included) after this method has returned.

§Example
use std::time::Duration;

use fm_rs::{GenerationOptions, Session, SystemLanguageModel};
use serde_json::json;

let model = SystemLanguageModel::new()?;
let session = Session::new(&model)?;
let schema = json!({
    "type": "object",
    "properties": { "answer": { "type": "string" } },
    "required": ["answer"]
});

let response = session.respond_json_with_timeout(
    "Answer briefly",
    &schema,
    &GenerationOptions::default(),
    Duration::from_secs(30),
)?;
let json: serde_json::Value = serde_json::from_str(response.content())?;
Source

pub fn respond_structured<T: DeserializeOwned>( &self, prompt: &str, schema: &Value, options: &GenerationOptions, ) -> Result<T>

Sends a prompt and returns a deserialized structured response.

This is a convenience method that calls respond_json and deserializes the result into the specified type.

§Example
use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
use serde::Deserialize;
use serde_json::json;

#[derive(Deserialize)]
struct Person {
    name: String,
    age: u32,
}

let model = SystemLanguageModel::new()?;
let session = Session::new(&model)?;

let schema = json!({
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "age": { "type": "integer" }
    },
    "required": ["name", "age"]
});

let person: Person = session.respond_structured(
    "Generate a fictional person",
    &schema,
    &GenerationOptions::default()
)?;
Source

pub fn respond_structured_gen<T>( &self, prompt: &str, options: &GenerationOptions, ) -> Result<T>

Sends a prompt and returns a deserialized structured response using a derived schema.

This uses the crate::Generable implementation to obtain the JSON schema.

Source

pub fn stream_json<F>( &self, prompt: &str, schema: &Value, options: &GenerationOptions, on_chunk: F, ) -> Result<()>
where F: FnMut(&str) + Send,

Streams a structured JSON response.

Unlike stream_response, on_chunk receives the cumulative partial JSON generated so far on each call, not an incremental delta — render each snapshot in place rather than concatenating them. Partial snapshots may not be valid JSON until streaming completes.

§Example
use fm_rs::{Session, SystemLanguageModel, GenerationOptions};
use serde_json::json;

let model = SystemLanguageModel::new()?;
let session = Session::new(&model)?;

let schema = json!({
    "type": "object",
    "properties": {
        "items": { "type": "array", "items": { "type": "string" } }
    }
});

session.stream_json(
    "List 5 programming languages",
    &schema,
    &GenerationOptions::default(),
    |chunk| {
        print!("{chunk}");
    }
)?;

Trait Implementations§

Source§

impl Drop for Session

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Send for Session

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.