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
impl LanguageModelSession
Sourcepub fn new() -> Self
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.
Sourcepub fn with_instructions(instructions: &str) -> Self
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.
Sourcepub fn try_new(instructions: Option<&str>) -> Option<Self>
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.
Sourcepub fn prewarm(&self)
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.
Sourcepub fn is_responding(&self) -> bool
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).
Sourcepub fn respond_with_json_schema(
&self,
prompt: &str,
schema_description: &str,
) -> Result<String, FMError>
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.