Skip to main content

ferrum_interfaces/
engine.rs

1//! Inference engine interfaces — split per modality.
2//!
3//! Phase 5a step 2 splits the historical mega-trait (which mixed LLM
4//! generation, embedding, transcription, and TTS in one) into a base
5//! lifecycle trait and four modality-specific supertraits. Each
6//! engine impl now implements exactly the trait its modality needs;
7//! no more inert "unsupported" stubs.
8
9use async_trait::async_trait;
10use ferrum_types::{
11    EngineConfig, ExecutorAdmissionSnapshot, InferenceRequest, InferenceResponse, Result,
12    StreamChunk,
13};
14use futures::Stream;
15use std::pin::Pin;
16
17/// Lifecycle / status methods shared by every engine kind.
18///
19/// LLM engines, embedders, transcribers, and TTS services all expose
20/// the same minimal status/metrics surface to the server / CLI. The
21/// modality-specific traits below extend this base.
22#[async_trait]
23pub trait InferenceEngine: Send + Sync {
24    /// Get current engine status.
25    async fn status(&self) -> ferrum_types::EngineStatus;
26
27    /// Shutdown engine gracefully.
28    async fn shutdown(&self) -> Result<()>;
29
30    /// Get engine configuration.
31    fn config(&self) -> &EngineConfig;
32
33    /// Get engine metrics.
34    fn metrics(&self) -> ferrum_types::EngineMetrics;
35
36    /// Health check.
37    async fn health_check(&self) -> ferrum_types::HealthStatus;
38
39    /// Optional cache metrics emitted by concrete LLM engines.
40    ///
41    /// The default keeps non-LLM and stub engines source-compatible. Real
42    /// engines can expose prefix/session cache counters without forcing those
43    /// fields into every modality's core metrics type.
44    fn cache_metrics_snapshot(&self) -> Option<serde_json::Value> {
45        None
46    }
47
48    /// Optional compact provider-attribution witness from the active model
49    /// executor. The default keeps non-vNext engines source-compatible.
50    fn execution_attribution_snapshot(&self) -> Option<serde_json::Value> {
51        None
52    }
53
54    /// Runtime-authoritative admission state. Startup sizing estimates are
55    /// intentionally not accepted through this method.
56    fn admission_snapshot(&self) -> Result<Option<ExecutorAdmissionSnapshot>> {
57        Ok(None)
58    }
59
60    /// Optional LoRA runtime metrics emitted by concrete LLM engines.
61    fn lora_metrics_snapshot(&self) -> Option<serde_json::Value> {
62        None
63    }
64}
65
66/// LLM text-generation engine.
67///
68/// Implemented by `ContinuousBatchEngine` (the production path) and
69/// `DefaultInferenceEngine` (legacy reference path). Backs
70/// `/v1/chat/completions` and `/v1/completions`.
71#[async_trait]
72pub trait LlmInferenceEngine: InferenceEngine {
73    /// Execute single inference request.
74    async fn infer(&self, request: InferenceRequest) -> Result<InferenceResponse>;
75
76    /// Execute streaming inference request.
77    async fn infer_stream(
78        &self,
79        request: InferenceRequest,
80    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send>>>;
81}
82
83/// Embedding engine (CLIP, BERT, etc.).
84///
85/// Backs `/v1/embeddings`. Distinct from LLM engines — no token
86/// generation, no scheduling, no KV cache.
87#[async_trait]
88pub trait EmbedEngine: InferenceEngine {
89    /// Embed raw text string → float vector (engine handles tokenization).
90    async fn embed_text(&self, text: &str) -> Result<Vec<f32>>;
91
92    /// Embed image (file path or base64) → float vector.
93    async fn embed_image(&self, image: &str) -> Result<Vec<f32>>;
94
95    /// Get embedding dimension.
96    fn embedding_dim(&self) -> usize;
97}
98
99/// Speech-to-text (Whisper) engine.
100///
101/// Backs `/v1/audio/transcriptions`.
102#[async_trait]
103pub trait TranscribeEngine: InferenceEngine {
104    /// Transcribe audio file → text.
105    async fn transcribe_file(&self, path: &str, language: Option<&str>) -> Result<String>;
106
107    /// Transcribe audio bytes (WAV / etc.) → text.
108    async fn transcribe_bytes(&self, data: &[u8], language: Option<&str>) -> Result<String>;
109}
110
111/// Text-to-speech (Qwen3-TTS, etc.) engine.
112///
113/// Backs `/v1/audio/speech`.
114#[async_trait]
115pub trait TtsEngine: InferenceEngine {
116    /// Synthesize speech → PCM audio chunks (streaming).
117    /// Returns Vec of PCM f32 samples per chunk.
118    async fn synthesize_speech(
119        &self,
120        text: &str,
121        language: Option<&str>,
122        chunk_frames: usize,
123    ) -> Result<Vec<Vec<f32>>>;
124
125    /// Get TTS sample rate.
126    fn tts_sample_rate(&self) -> u32;
127}
128
129/// Advanced engine capabilities — opt-in addition to LLM engines that
130/// support batching / speculation / runtime reconfig / diagnostics.
131#[async_trait]
132pub trait AdvancedInferenceEngine: LlmInferenceEngine {
133    /// Execute batch inference.
134    async fn infer_batch(
135        &self,
136        requests: Vec<InferenceRequest>,
137    ) -> Result<Vec<Result<InferenceResponse>>>;
138
139    /// Execute speculative inference.
140    async fn infer_speculative(
141        &self,
142        request: InferenceRequest,
143        speculation_config: ferrum_types::SpeculationConfig,
144    ) -> Result<InferenceResponse>;
145
146    /// Warm up engine with sample requests.
147    async fn warmup(
148        &mut self,
149        warmup_requests: Vec<InferenceRequest>,
150    ) -> Result<ferrum_types::WarmupResult>;
151
152    /// Configure engine at runtime.
153    async fn reconfigure(&mut self, config: EngineConfig) -> Result<()>;
154
155    /// Get detailed diagnostics.
156    async fn diagnostics(&self) -> ferrum_types::DiagnosticsReport;
157
158    /// Export engine state for debugging.
159    async fn export_state(&self) -> Result<ferrum_types::EngineState>;
160
161    /// Import engine state for debugging/testing.
162    async fn import_state(&mut self, state: ferrum_types::EngineState) -> Result<()>;
163}
164
165/// Speculation configuration for speculative decoding.
166pub type SpeculationConfig = ferrum_types::SpeculationConfig;
167
168/// Hardware constraints alias.
169pub type HardwareConstraints = ferrum_types::HardwareConstraints;
170
171/// Request characteristics alias.
172pub type RequestCharacteristics = ferrum_types::RequestCharacteristics;
173
174/// Latency requirements alias.
175pub type LatencyRequirements = ferrum_types::LatencyRequirements;