pub struct ChatEngine { /* private fields */ }Expand description
A reusable on-device LLM chat inference engine.
Thread-safe (Send + Sync) — safe to store in a once_cell::sync::Lazy,
tokio::sync::OnceCell, or shared application state.
All mutating operations acquire an internal tokio::sync::Mutex. The
mutex is released before the actual (potentially slow) model inference
runs, so other tasks can still query status or history while generation
is in progress.
Implementations§
Source§impl ChatEngine
impl ChatEngine
Sourcepub fn new() -> ChatEngine
pub fn new() -> ChatEngine
Create a new engine with no model loaded and no Onde app association.
Pulse telemetry is still enabled, but events carry no onde_app_id.
Sourcepub fn with_app_id(onde_app_id: Option<String>) -> ChatEngine
pub fn with_app_id(onde_app_id: Option<String>) -> ChatEngine
Create a new engine that reports telemetry for a specific Onde app.
The app UUID is threaded into every pulse event so the document store
associates rows with the right app. Consumer apps that know their ID
call ChatEngine::with_app_id(Some(smbcloud::onde_app_id())); the
UniFFI OndeChatEngine keeps calling new() (→ None).
Sourcepub async fn load_gguf_model(
&self,
config: GgufModelConfig,
system_prompt: Option<String>,
sampling: Option<SamplingConfig>,
) -> Result<Duration, InferenceError>
pub async fn load_gguf_model( &self, config: GgufModelConfig, system_prompt: Option<String>, sampling: Option<SamplingConfig>, ) -> Result<Duration, InferenceError>
Load a GGUF model into the engine.
If a model is already loaded it will be unloaded first (the previous
Model is dropped, which terminates its engine thread).
§Arguments
config— Which model to load (repo ID, filename, etc.).system_prompt— Optional system prompt to prepend to every request.sampling— Sampling parameters; passNonefor platform-aware defaults (mobile getsSamplingConfig::mobile, desktop getsSamplingConfig::default).
§Errors
Returns InferenceError::ModelBuild if the model fails to download
or load.
Sourcepub async fn load_uqff_model(
&self,
config: UqffModelConfig,
system_prompt: Option<String>,
sampling: Option<SamplingConfig>,
) -> Result<Duration, InferenceError>
pub async fn load_uqff_model( &self, config: UqffModelConfig, system_prompt: Option<String>, sampling: Option<SamplingConfig>, ) -> Result<Duration, InferenceError>
Load a UQFF model into the engine.
UQFF stores pre-quantised weights and loads directly
without runtime conversion. config.model_id is still required for
tokenizer and base model config resolution; config.files contains the
first shard or explicit UQFF shard filenames.
If a model is already loaded it will be unloaded first.
§Errors
Returns InferenceError::ModelBuild if the model fails to download
or load.
Sourcepub async fn load_assigned_model(
&self,
environment: Environment,
onde_app_id: &str,
onde_app_secret: &str,
system_prompt: Option<String>,
sampling: Option<SamplingConfig>,
) -> Result<Duration, InferenceError>
pub async fn load_assigned_model( &self, environment: Environment, onde_app_id: &str, onde_app_secret: &str, system_prompt: Option<String>, sampling: Option<SamplingConfig>, ) -> Result<Duration, InferenceError>
Fetch the model assigned to this Onde app from the SDK model-config endpoint and load it.
Authenticates using the app’s own onde_app_id + onde_app_secret
(the SDK credentials shown in the ondeinference.com dashboard).
No end-user JWT is required — model assignment is an operator-level
configuration that is independent of which user is currently signed in.
Fallback behaviour:
- HTTP 404 (no model assigned) → loads
GgufModelConfig::platform_default(). - Missing
hf_repo_idorgguf_filein response → loads platform default. - Any HTTP or network error → returns
InferenceError::ModelBuildso the caller can apply its own fallback.
Sourcepub async fn unload_model(&self) -> Option<String>
pub async fn unload_model(&self) -> Option<String>
Unload the current model, freeing all memory.
Dropping the Model sends a Terminate message to the mistral.rs
engine thread, which tears down the KV cache, activations, and model
weights.
Returns the display name of the model that was unloaded, or None
if no model was loaded.
Sourcepub async fn info(&self) -> EngineInfo
pub async fn info(&self) -> EngineInfo
Get a snapshot of the engine’s current state.
Sourcepub async fn set_system_prompt(&self, prompt: impl Into<String>)
pub async fn set_system_prompt(&self, prompt: impl Into<String>)
Set or replace the system prompt.
The system prompt is prepended to every inference request (it is NOT stored in the conversation history).
Sourcepub async fn clear_system_prompt(&self)
pub async fn clear_system_prompt(&self)
Clear the system prompt.
Sourcepub async fn set_sampling(&self, sampling: SamplingConfig)
pub async fn set_sampling(&self, sampling: SamplingConfig)
Replace the sampling configuration.
Sourcepub async fn history(&self) -> Vec<ChatMessage>
pub async fn history(&self) -> Vec<ChatMessage>
Get a clone of the full conversation history.
Tool-related history entries are converted back to plain
ChatMessage values (assistant tool-call entries become assistant
messages with just their text content; tool results are omitted).
Sourcepub async fn clear_history(&self) -> usize
pub async fn clear_history(&self) -> usize
Clear the conversation history but keep the model loaded.
Returns the number of turns that were removed.
Sourcepub async fn push_history(&self, message: ChatMessage)
pub async fn push_history(&self, message: ChatMessage)
Append a message to history without running inference.
Useful for restoring a saved conversation or injecting context.
Sourcepub async fn send_message(
&self,
user_message: impl Into<String>,
) -> Result<InferenceResult, InferenceError>
pub async fn send_message( &self, user_message: impl Into<String>, ) -> Result<InferenceResult, InferenceError>
Send a user message and receive a complete assistant reply.
The user message and assistant reply are automatically appended to the conversation history on success.
§Errors
InferenceError::NoModelLoadedif no model is loaded.InferenceError::Inferenceif the model fails to generate.
Sourcepub async fn generate(
&self,
messages: Vec<ChatMessage>,
sampling: Option<SamplingConfig>,
) -> Result<InferenceResult, InferenceError>
pub async fn generate( &self, messages: Vec<ChatMessage>, sampling: Option<SamplingConfig>, ) -> Result<InferenceResult, InferenceError>
Run inference on an explicit list of messages WITHOUT modifying the engine’s internal history.
This is useful for one-shot prompts (e.g. prompt enhancement) where you don’t want side-effects on the main conversation.
The system prompt set on the engine is still prepended.
Sourcepub async fn stream_message(
&self,
user_message: impl Into<String>,
) -> Result<Receiver<StreamChunk>, InferenceError>
pub async fn stream_message( &self, user_message: impl Into<String>, ) -> Result<Receiver<StreamChunk>, InferenceError>
Send a user message and receive an async stream of token chunks.
The user message and full assembled reply are automatically appended to the conversation history once the stream finishes.
§Returns
A tokio::sync::mpsc::Receiver<StreamChunk>. The caller should
receive from it until chunk.done == true or the channel closes.
§Errors
Returns immediately with InferenceError::NoModelLoaded if no
model is loaded. Inference errors are delivered as the final chunk
with done = true and an empty delta.
Sourcepub async fn tool_calling_support(&self) -> ToolCallingSupport
pub async fn tool_calling_support(&self) -> ToolCallingSupport
Whether the currently loaded model is verified for structured tool calls.
Returns Unsupported when no model
is loaded: an engine with nothing in it cannot produce tool calls, and
reporting Unknown there would conflate an empty engine with a model
repository Onde has not catalogued.
Sourcepub async fn send_message_with_tools(
&self,
user_message: impl Into<String>,
tools: &[ToolDefinition],
) -> Result<ToolAwareResult, InferenceError>
pub async fn send_message_with_tools( &self, user_message: impl Into<String>, tools: &[ToolDefinition], ) -> Result<ToolAwareResult, InferenceError>
Send a user message with tool definitions available. Non-streaming.
If the model decides to call tools, ToolAwareResult::tool_calls
will be non-empty and finish_reason will typically be "tool_calls".
The user message and response (including any tool calls) are automatically added to conversation history.
Sourcepub async fn send_tool_results(
&self,
results: Vec<ToolResult>,
tools: Option<&[ToolDefinition]>,
) -> Result<ToolAwareResult, InferenceError>
pub async fn send_tool_results( &self, results: Vec<ToolResult>, tools: Option<&[ToolDefinition]>, ) -> Result<ToolAwareResult, InferenceError>
Send tool execution results back to the model. Non-streaming.
Call this after executing the tools from a previous
send_message_with_tools response.
Pass the same (or updated) tool definitions if the model should be
allowed to make further tool calls.
Sourcepub async fn record_tool_results(&self, results: Vec<ToolResult>) -> usize
pub async fn record_tool_results(&self, results: Vec<ToolResult>) -> usize
Append tool results to history without starting another inference round.
Agent hosts use this when a turn is cancelled after the assistant has requested tools. Recording a result for every request keeps the history structurally valid for the next turn.
Only results answering a call the assistant actually requested, and not
already recorded, are appended. Anything else is dropped with a warning:
a ToolResult with no matching AssistantToolCall ahead of it builds a
message sequence the model cannot interpret, and silently writing one
corrupts every subsequent turn rather than the current one. Returns how
many results were appended.
Sourcepub async fn stream_tool_results(
&self,
results: Vec<ToolResult>,
tools: Option<Vec<ToolDefinition>>,
) -> Result<Receiver<StreamChunk>, InferenceError>
pub async fn stream_tool_results( &self, results: Vec<ToolResult>, tools: Option<Vec<ToolDefinition>>, ) -> Result<Receiver<StreamChunk>, InferenceError>
Stream tool execution results back to the model.
Similar to send_tool_results but returns
a streaming receiver. Tool calls in the streaming response are NOT
parsed — this is intended for the final text response after all tool
rounds complete.
Trait Implementations§
Source§impl Default for ChatEngine
Available on Android or iOS or Linux or macOS or tvOS or visionOS or watchOS or Windows only.
impl Default for ChatEngine
Source§fn default() -> ChatEngine
fn default() -> ChatEngine
Auto Trait Implementations§
impl !Freeze for ChatEngine
impl !RefUnwindSafe for ChatEngine
impl !UnwindSafe for ChatEngine
impl Send for ChatEngine
impl Sync for ChatEngine
impl Unpin for ChatEngine
impl UnsafeUnpin for ChatEngine
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Downcast for T
impl<T> Downcast for T
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T, UT> HandleAlloc<UT> for T
impl<T, UT> HandleAlloc<UT> for T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<R, P> ReadPrimitive<R> for P
impl<R, P> ReadPrimitive<R> for P
Source§fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
ReadEndian::read_from_little_endian().Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.