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
impl Session
Sourcepub fn builder<M: LanguageModel + ?Sized>(model: &M) -> SessionBuilder<'_, M>
pub fn builder<M: LanguageModel + ?Sized>(model: &M) -> SessionBuilder<'_, M>
Creates a session builder for combining instructions, tools, and built-in system tools.
Sourcepub fn new<M: LanguageModel + ?Sized>(model: &M) -> Result<Self>
pub fn new<M: LanguageModel + ?Sized>(model: &M) -> Result<Self>
Creates a new session with the given model.
Sourcepub fn with_instructions<M: LanguageModel + ?Sized>(
model: &M,
instructions: &str,
) -> Result<Self>
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.
Sourcepub fn with_tools<M: LanguageModel + ?Sized>(
model: &M,
tools: &[Arc<dyn Tool>],
) -> Result<Self>
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.
Sourcepub fn with_instructions_and_tools<M: LanguageModel + ?Sized>(
model: &M,
instructions: &str,
tools: &[Arc<dyn Tool>],
) -> Result<Self>
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.
Sourcepub fn from_transcript<M: LanguageModel + ?Sized>(
model: &M,
transcript_json: &str,
) -> Result<Self>
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.
Sourcepub fn respond(
&self,
prompt: &str,
options: &GenerationOptions,
) -> Result<Response>
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.
Sourcepub fn respond_with_reasoning(
&self,
prompt: &str,
options: &GenerationOptions,
reasoning_level: ReasoningLevel,
) -> Result<Response>
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.
Sourcepub fn respond_with_reasoning_timeout(
&self,
prompt: &str,
options: &GenerationOptions,
reasoning_level: ReasoningLevel,
timeout: Duration,
) -> Result<Response>
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.
Sourcepub fn respond_with_timeout(
&self,
prompt: &str,
options: &GenerationOptions,
timeout: Duration,
) -> Result<Response>
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.
Sourcepub fn stream_response<F>(
&self,
prompt: &str,
options: &GenerationOptions,
on_chunk: F,
) -> Result<()>
pub fn stream_response<F>( &self, prompt: &str, options: &GenerationOptions, on_chunk: F, ) -> Result<()>
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);
})?;Sourcepub fn respond_with_attachments(
&self,
prompt: &str,
attachments: &[Attachment<'_>],
options: &GenerationOptions,
) -> Result<Response>
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.
Sourcepub fn usage(&self) -> Result<SessionUsage>
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.
Sourcepub fn set_transcript(&self, transcript_json: &str) -> Result<()>
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.
Sourcepub fn set_transcript_error_handling_policy(
&self,
policy: Option<TranscriptErrorHandlingPolicy>,
) -> Result<()>
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.
Sourcepub fn cancel(&self)
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.
Sourcepub fn cancellation_handle(&self) -> CancellationHandle
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");Sourcepub fn is_responding(&self) -> bool
pub fn is_responding(&self) -> bool
Checks if the session is currently generating a response.
Sourcepub fn transcript_json(&self) -> Result<String>
pub fn transcript_json(&self) -> Result<String>
Gets the session transcript as a JSON string.
This can be used to persist and restore conversations.
Sourcepub fn context_usage(&self, limit: &ContextLimit) -> Result<ContextUsage>
pub fn context_usage(&self, limit: &ContextLimit) -> Result<ContextUsage>
Estimates current context usage based on the session transcript.
Sourcepub fn ensure_context_within(&self, limit: &ContextLimit) -> Result<()>
pub fn ensure_context_within(&self, limit: &ContextLimit) -> Result<()>
Returns an error if the estimated context usage exceeds the configured limit.
Sourcepub fn prewarm(&self, prompt_prefix: Option<&str>) -> Result<()>
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.
Sourcepub fn respond_json(
&self,
prompt: &str,
schema: &Value,
options: &GenerationOptions,
) -> Result<String>
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)?;Sourcepub fn respond_json_with_timeout(
&self,
prompt: &str,
schema: &Value,
options: &GenerationOptions,
timeout: Duration,
) -> Result<Response>
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())?;Sourcepub fn respond_structured<T: DeserializeOwned>(
&self,
prompt: &str,
schema: &Value,
options: &GenerationOptions,
) -> Result<T>
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()
)?;Sourcepub fn respond_structured_gen<T>(
&self,
prompt: &str,
options: &GenerationOptions,
) -> Result<T>where
T: Generable + DeserializeOwned,
pub fn respond_structured_gen<T>(
&self,
prompt: &str,
options: &GenerationOptions,
) -> Result<T>where
T: Generable + DeserializeOwned,
Sends a prompt and returns a deserialized structured response using a derived schema.
This uses the crate::Generable implementation to obtain the JSON schema.
Sourcepub fn stream_json<F>(
&self,
prompt: &str,
schema: &Value,
options: &GenerationOptions,
on_chunk: F,
) -> Result<()>
pub fn stream_json<F>( &self, prompt: &str, schema: &Value, options: &GenerationOptions, on_chunk: F, ) -> Result<()>
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}");
}
)?;