Skip to main content

LanguageModelSession

Struct LanguageModelSession 

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

A stateful conversation with the on-device language model.

Sessions retain their conversation history; subsequent calls to respond build on the previous turns.

§Examples

use foundation_models::LanguageModelSession;

let session = LanguageModelSession::new();
let answer = session.respond("Name three Norse gods.")?;
println!("{answer}");

Implementations§

Source§

impl LanguageModelSession

Source

pub fn new() -> Self

Create a session with the model’s default behaviour.

§Panics

Panics if FoundationModels is not available on this OS. Check crate::SystemLanguageModel::is_available first if you need to handle that gracefully.

Source

pub fn with_instructions(instructions: &str) -> Self

Create a session with custom system instructions (“system prompt”).

§Panics

Panics if FoundationModels is not available, or if instructions contains an interior NUL byte.

Source

pub fn try_new(instructions: Option<&str>) -> Option<Self>

Fallible constructor. Returns None when FoundationModels is not available (OS too old, model not enabled, etc.) or when instructions contains an interior NUL byte.

Source

pub fn respond(&self, prompt: &str) -> Result<String, FMError>

Send a prompt and block until the full response is available.

§Errors

Returns an FMError if the model rejects the prompt, the context window is exceeded, the session is cancelled, or the prompt contains an interior NUL byte.

Source

pub fn prewarm(&self)

Pre-warm the model. Apple loads the weights + initialises the inference engine so the next respond call is faster. Returns immediately; the warm-up runs in the background.

Source

pub fn is_responding(&self) -> bool

True if this session is currently producing a response (i.e. an earlier respond / stream is still in flight on Apple’s queue).

Source

pub fn transcript_json(&self) -> String

Return a best-effort JSON serialisation of the session’s Transcript — the full history of user prompts and model responses. Useful for persisting a chat session across process boundaries.

Source

pub fn log_feedback(&self, sentiment: i32, description: Option<&str>)

Log feedback on the most recent response for diagnostic / fine-tuning purposes. sentiment: 1 positive, 0 neutral, -1 negative.

Source

pub fn respond_with_json_schema( &self, prompt: &str, schema_description: &str, ) -> Result<String, FMError>

Prompt-engineered JSON-shape response.

Wraps the prompt with a “respond with valid JSON matching this schema” instruction and parses the response. The schema is a serde_json::Value-style JSON string (passed as text).

Useful for getting structured data out of the model without the full Generable macro machinery. The model still returns plain text — the caller must parse with serde_json / serde after.

§Errors

See respond.

Source

pub fn respond_with( &self, prompt: &str, options: GenerationOptions, ) -> Result<String, FMError>

Like respond, but with explicit generation options.

§Errors

See respond.

Source

pub fn respond_with_schema( &self, prompt: &str, schema: &str, include_schema_in_prompt: bool, ) -> Result<String, FMError>

Schema-driven structured response.

Builds a DynamicGenerationSchema from the provided JSON schema, runs LanguageModelSession.respond(schema:prompt:), and returns the model’s GeneratedContent.jsonString — a well-formed JSON string matching the requested shape.

Supported schema shape (strict subset of JSON Schema):

{
  "type": "object",
  "name": "Movie",
  "properties": {
    "title":  { "type": "string", "description": "Movie title" },
    "year":   { "type": "integer" },
    "rating": { "type": "number", "optional": true },
    "tags":   { "type": "array", "items": { "type": "string" }, "min": 1, "max": 5 }
  }
}

Primitive types: "string", "integer", "number", "boolean", "array", "object". Each property may set "description" and "optional". Array schemas accept "items" plus optional "min" / "max" element counts.

§Errors

See respond for general errors, plus a “schema build failed” / “schema JSON is not valid” error returned as FMError::Unknown if the schema is malformed.

Source

pub fn respond_with_schema_options( &self, prompt: &str, schema: &str, include_schema_in_prompt: bool, options: GenerationOptions, ) -> Result<String, FMError>

respond_with_schema with explicit generation options.

§Errors

See respond_with_schema.

Source

pub fn stream<F>(&self, prompt: &str, on_chunk: F) -> Result<(), FMError>
where F: FnMut(StreamEvent<'_>) + Send + 'static,

Stream the response as the model generates it. The callback is invoked with each delta and a final invocation with done == true.

§Errors

Returns an FMError mirroring respond. The callback may also receive a chunk and an error if the stream fails midway.

Source

pub fn stream_with<F>( &self, prompt: &str, options: GenerationOptions, on_chunk: F, ) -> Result<(), FMError>
where F: FnMut(StreamEvent<'_>) + Send + 'static,

Like stream, but with explicit generation options.

§Errors

See stream.

Trait Implementations§

Source§

impl Debug for LanguageModelSession

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for LanguageModelSession

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for LanguageModelSession

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 LanguageModelSession

Source§

impl Sync for LanguageModelSession

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.