Skip to main content

ChatEngine

Struct ChatEngine 

Source
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

Source

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.

Source

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).

Source

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; pass None for platform-aware defaults (mobile gets SamplingConfig::mobile, desktop gets SamplingConfig::default).
§Errors

Returns InferenceError::ModelBuild if the model fails to download or load.

Source

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.

Source

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:

Source

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.

Source

pub async fn is_loaded(&self) -> bool

Check whether a model is currently loaded.

Source

pub async fn info(&self) -> EngineInfo

Get a snapshot of the engine’s current state.

Source

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).

Source

pub async fn clear_system_prompt(&self)

Clear the system prompt.

Source

pub async fn set_sampling(&self, sampling: SamplingConfig)

Replace the sampling configuration.

Source

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).

Source

pub async fn clear_history(&self) -> usize

Clear the conversation history but keep the model loaded.

Returns the number of turns that were removed.

Source

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.

Source

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
Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.
Source§

fn default() -> ChatEngine

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

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> AsAny for T
where T: Any,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Source§

fn type_name(&self) -> &'static str

Gets the type name of self
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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CompatExt for T

Source§

fn compat(self) -> Compat<T> ⓘ
where T: Sized,

Applies the Compat adapter by value. Read more
Source§

fn compat_ref(&self) -> Compat<&T> ⓘ

Applies the Compat adapter by shared reference. Read more
Source§

fn compat_mut(&mut self) -> Compat<&mut T> ⓘ

Applies the Compat adapter by mutable reference. Read more
Source§

impl<T> Downcast for T
where T: AsAny + ?Sized,

Source§

fn is<T>(&self) -> bool
where T: AsAny,

Returns true if the boxed type is the same as T. Read more
Source§

fn downcast_ref<T>(&self) -> Option<&T>
where T: AsAny,

Forward to the method defined on the type Any.
Source§

fn downcast_mut<T>(&mut self) -> Option<&mut T>
where T: AsAny,

Forward to the method defined on the type Any.
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, UT> HandleAlloc<UT> for T
where T: Send + Sync,

Source§

fn new_handle(value: Arc<T>) -> Handle

Create a new handle for an Arc value Read more
Source§

unsafe fn clone_handle(handle: Handle) -> Handle

Clone a handle Read more
Source§

unsafe fn consume_handle(handle: Handle) -> Arc<T> ⓘ

Consume a handle, getting back the initial Arc<> Read more
Source§

unsafe fn get_arc(handle: Handle) -> Arc<Self> ⓘ

Get a clone of the Arc<> using a “borrowed” handle. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
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.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more