mistralrs_core/
lib.rs

1#![deny(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
2use candle_core::Device;
3use engine::Engine;
4pub use engine::{
5    get_engine_terminate_flag, reset_engine_terminate_flag, should_terminate_engine_sequences,
6    EngineInstruction, SearchEmbeddingModel, ENGINE_INSTRUCTIONS, TERMINATE_ALL_NEXT_STEP,
7};
8use hf_hub::Cache;
9pub use lora::Ordering;
10pub use pipeline::ModelCategory;
11pub use pipeline::Pipeline;
12#[cfg(feature = "pyo3_macros")]
13use pyo3::exceptions::PyValueError;
14use std::collections::HashMap;
15use std::num::NonZeroUsize;
16use std::sync::OnceLock;
17use std::time::Instant;
18use std::{
19    cell::RefCell,
20    error::Error,
21    fs::OpenOptions,
22    io::Write,
23    sync::{atomic::AtomicBool, Arc, Mutex, RwLock},
24    thread::{self, JoinHandle},
25    time::{SystemTime, UNIX_EPOCH},
26};
27use tokio::sync::mpsc::{channel, Sender};
28use tracing::info;
29use tracing::warn;
30
31mod cuda;
32mod device_map;
33mod engine;
34mod lora;
35mod model_loader;
36mod moe;
37mod ops;
38pub use model_loader::{
39    get_auto_device_map_params, get_model_dtype, get_tgt_non_granular_index, LoaderBuilder,
40};
41mod embedding_models;
42mod kv_cache;
43mod search;
44
45mod model_selected;
46pub use model_selected::ModelSelected;
47pub use toml_selector::{get_toml_selected_model_device_map_params, get_toml_selected_model_dtype};
48
49mod amoe;
50mod attention;
51mod diffusion_models;
52pub mod distributed;
53mod gguf;
54pub mod layers;
55mod layers_masker;
56mod layers_utils;
57pub mod matformer;
58mod models;
59mod paged_attention;
60mod pipeline;
61mod prefix_cacher;
62mod request;
63mod response;
64mod sampler;
65mod scheduler;
66mod sequence;
67mod speech_models;
68mod toml_selector;
69mod tools;
70mod topology;
71mod utils;
72mod vision_models;
73mod xlora_models;
74
75pub use amoe::{AnyMoeConfig, AnyMoeExpertType};
76pub use device_map::{
77    DeviceLayerMapMetadata, DeviceMapMetadata, DeviceMapSetting, LayerDeviceMapper,
78};
79pub use gguf::{GGUFArchitecture, GGUF_MULTI_FILE_DELIMITER};
80pub use mistralrs_audio::AudioInput;
81pub use mistralrs_mcp::{
82    CalledFunction, Function, Tool, ToolCallback, ToolCallbackWithTool, ToolType,
83};
84pub use mistralrs_mcp::{
85    McpClient, McpClientConfig, McpServerConfig, McpServerSource, McpToolInfo,
86};
87pub use mistralrs_quant::{IsqType, MULTI_LORA_DELIMITER};
88pub use paged_attention::{MemoryGpuConfig, PagedAttentionConfig, PagedCacheType};
89pub use pipeline::{
90    chat_template::ChatTemplate, parse_isq_value, AdapterPaths, AnyMoeLoader, AnyMoePipeline,
91    AutoDeviceMapParams, AutoLoader, AutoLoaderBuilder, DiffusionGenerationParams, DiffusionLoader,
92    DiffusionLoaderBuilder, DiffusionLoaderType, EmbeddingLoader, EmbeddingLoaderBuilder,
93    EmbeddingLoaderType, EmbeddingModelPaths, EmbeddingSpecificConfig, GGMLLoader,
94    GGMLLoaderBuilder, GGMLSpecificConfig, GGUFLoader, GGUFLoaderBuilder, GGUFSpecificConfig,
95    GemmaLoader, Idefics2Loader, IsqOrganization, LLaVALoader, LLaVANextLoader, LlamaLoader,
96    Loader, LocalModelPaths, LoraAdapterPaths, MistralLoader, MixtralLoader, Modalities, ModelKind,
97    ModelPaths, MultimodalPromptPrefixer, NormalLoader, NormalLoaderBuilder, NormalLoaderType,
98    NormalSpecificConfig, Phi2Loader, Phi3Loader, Phi3VLoader, Qwen2Loader, SpeculativeConfig,
99    SpeculativeLoader, SpeculativePipeline, SpeechLoader, SpeechPipeline, Starcoder2Loader,
100    SupportedModality, TokenSource, VisionLoader, VisionLoaderBuilder, VisionLoaderType,
101    VisionSpecificConfig, UQFF_MULTI_FILE_DELIMITER,
102};
103pub use request::{
104    ApproximateUserLocation, Constraint, DetokenizationRequest, ImageGenerationResponseFormat,
105    LlguidanceGrammar, MessageContent, NormalRequest, Request, RequestMessage, SearchContextSize,
106    TokenizationRequest, WebSearchOptions, WebSearchUserLocation,
107};
108pub use response::*;
109pub use sampler::{
110    CustomLogitsProcessor, DrySamplingParams, SamplingParams, StopTokens, TopLogprob,
111};
112pub use scheduler::{DefaultSchedulerMethod, SchedulerConfig};
113pub use search::{SearchCallback, SearchFunctionParameters, SearchResult};
114use serde::Serialize;
115pub use speech_models::{utils as speech_utils, SpeechGenerationConfig, SpeechLoaderType};
116use tokio::runtime::Runtime;
117use toml_selector::{TomlLoaderArgs, TomlSelector};
118pub use tools::{ToolCallResponse, ToolCallType, ToolCallbacks, ToolChoice};
119pub use topology::{LayerTopology, Topology};
120pub use utils::debug::initialize_logging;
121pub use utils::memory_usage::MemoryUsage;
122pub use utils::normal::{ModelDType, TryIntoDType};
123pub use utils::{paged_attn_supported, using_flash_attn};
124
125// re-export llguidance for easier LlguidanceGrammar construction
126pub use llguidance;
127
128/// `true` if `MISTRALRS_DEBUG=1`
129pub(crate) static DEBUG: AtomicBool = AtomicBool::new(false);
130pub static GLOBAL_HF_CACHE: OnceLock<Cache> = OnceLock::new();
131
132/// Configuration for creating an engine instance
133#[derive(Clone)]
134pub struct EngineConfig {
135    pub no_kv_cache: bool,
136    pub no_prefix_cache: bool,
137    pub prefix_cache_n: usize,
138    pub disable_eos_stop: bool,
139    pub throughput_logging_enabled: bool,
140    pub search_embedding_model: Option<SearchEmbeddingModel>,
141    pub search_callback: Option<Arc<SearchCallback>>,
142    pub tool_callbacks: tools::ToolCallbacks,
143    pub tool_callbacks_with_tools: tools::ToolCallbacksWithTools,
144}
145
146impl Default for EngineConfig {
147    fn default() -> Self {
148        Self {
149            no_kv_cache: false,
150            no_prefix_cache: false,
151            prefix_cache_n: 16,
152            disable_eos_stop: false,
153            throughput_logging_enabled: true,
154            search_embedding_model: None,
155            search_callback: None,
156            tool_callbacks: HashMap::new(),
157            tool_callbacks_with_tools: HashMap::new(),
158        }
159    }
160}
161
162/// Configuration for adding a model to MistralRs
163#[derive(Clone)]
164pub struct AddModelConfig {
165    pub engine_config: EngineConfig,
166    pub mcp_client_config: Option<McpClientConfig>,
167}
168
169impl AddModelConfig {
170    pub fn new(engine_config: EngineConfig) -> Self {
171        Self {
172            engine_config,
173            mcp_client_config: None,
174        }
175    }
176
177    pub fn with_mcp_config(mut self, mcp_config: McpClientConfig) -> Self {
178        self.mcp_client_config = Some(mcp_config);
179        self
180    }
181}
182
183#[derive(Clone)]
184pub struct MistralRsConfig {
185    pub kind: ModelKind,
186    pub device: Device,
187    pub category: ModelCategory,
188    pub modalities: Modalities,
189    pub max_seq_len: Option<usize>,
190}
191
192/// Internal structure to hold per-engine state
193struct EngineInstance {
194    sender: Sender<Request>,
195    engine_handler: JoinHandle<()>,
196    reboot_state: RebootState,
197    config: MistralRsConfig,
198    category: ModelCategory,
199}
200
201/// The MistralRs struct handles sending requests to multiple engines.
202/// It is the core multi-threaded component of mistral.rs, and uses `mpsc`
203/// `Sender` and `Receiver` primitives to send and receive requests to the
204/// appropriate engine based on model ID.
205pub struct MistralRs {
206    engines: RwLock<HashMap<String, EngineInstance>>,
207    default_engine_id: RwLock<Option<String>>,
208    log: Option<String>,
209    id: String,
210    creation_time: u64,
211    next_request_id: Mutex<RefCell<usize>>,
212}
213
214#[derive(Clone)]
215struct RebootState {
216    pipeline: Arc<tokio::sync::Mutex<dyn Pipeline>>,
217    method: SchedulerConfig,
218    no_kv_cache: bool,
219    no_prefix_cache: bool,
220    prefix_cache_n: usize,
221    disable_eos_stop: bool,
222    throughput_logging_enabled: bool,
223    search_embedding_model: Option<SearchEmbeddingModel>,
224    search_callback: Option<Arc<search::SearchCallback>>,
225    tool_callbacks: tools::ToolCallbacks,
226    tool_callbacks_with_tools: tools::ToolCallbacksWithTools,
227    mcp_client_config: Option<McpClientConfig>,
228}
229
230#[derive(Debug)]
231pub enum MistralRsError {
232    EnginePoisoned,
233    SenderPoisoned,
234}
235
236impl std::fmt::Display for MistralRsError {
237    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238        write!(f, "{:?}", &self)
239    }
240}
241
242impl std::error::Error for MistralRsError {}
243
244#[cfg(feature = "pyo3_macros")]
245impl From<MistralRsError> for pyo3::PyErr {
246    fn from(value: MistralRsError) -> Self {
247        PyValueError::new_err(format!("{value:?}"))
248    }
249}
250
251/// The MistralRsBuilder takes the pipeline and a scheduler method and constructs
252/// an Engine and a MistralRs instance. The Engine runs on a separate thread, and the MistralRs
253/// instance stays on the calling thread.
254pub struct MistralRsBuilder {
255    pipeline: Arc<tokio::sync::Mutex<dyn Pipeline>>,
256    method: SchedulerConfig,
257    log: Option<String>,
258    no_kv_cache: Option<bool>,
259    no_prefix_cache: Option<bool>,
260    prefix_cache_n: Option<usize>,
261    disable_eos_stop: Option<bool>,
262    throughput_logging_enabled: bool,
263    search_embedding_model: Option<SearchEmbeddingModel>,
264    search_callback: Option<Arc<SearchCallback>>,
265    tool_callbacks: tools::ToolCallbacks,
266    tool_callbacks_with_tools: tools::ToolCallbacksWithTools,
267    mcp_client_config: Option<McpClientConfig>,
268}
269
270impl MistralRsBuilder {
271    /// Creates a new builder with the given pipeline, scheduler method, logging flag,
272    /// and optional embedding model for web search. To override the search callback,
273    /// use `.with_search_callback(...)` on the builder.
274    pub fn new(
275        pipeline: Arc<tokio::sync::Mutex<dyn Pipeline>>,
276        method: SchedulerConfig,
277        throughput_logging: bool,
278        search_embedding_model: Option<SearchEmbeddingModel>,
279    ) -> Self {
280        Self {
281            pipeline,
282            method,
283            log: None,
284            no_kv_cache: None,
285            no_prefix_cache: None,
286            prefix_cache_n: None,
287            disable_eos_stop: None,
288            throughput_logging_enabled: throughput_logging,
289            search_embedding_model,
290            search_callback: None,
291            tool_callbacks: HashMap::new(),
292            tool_callbacks_with_tools: HashMap::new(),
293            mcp_client_config: None,
294        }
295    }
296    pub fn with_log(mut self, log: String) -> Self {
297        self.log = Some(log);
298        self
299    }
300    pub fn with_opt_log(mut self, log: Option<String>) -> Self {
301        self.log = log;
302        self
303    }
304    pub fn with_no_kv_cache(mut self, no_kv_cache: bool) -> Self {
305        self.no_kv_cache = Some(no_kv_cache);
306        self
307    }
308    pub fn with_no_prefix_cache(mut self, no_prefix_cache: bool) -> Self {
309        self.no_prefix_cache = Some(no_prefix_cache);
310        self
311    }
312    pub fn with_prefix_cache_n(mut self, prefix_cache_n: usize) -> Self {
313        self.prefix_cache_n = Some(prefix_cache_n);
314        self
315    }
316    pub fn with_disable_eos_stop(mut self, disable_eos_stop: bool) -> Self {
317        self.disable_eos_stop = Some(disable_eos_stop);
318        self
319    }
320
321    /// Use a custom callback to gather search results.
322    pub fn with_search_callback(mut self, search_callback: Arc<SearchCallback>) -> Self {
323        self.search_callback = Some(search_callback);
324        self
325    }
326
327    /// Register a custom callback for the specified tool name.
328    pub fn with_tool_callback(
329        mut self,
330        name: impl Into<String>,
331        tool_callback: Arc<ToolCallback>,
332    ) -> Self {
333        self.tool_callbacks.insert(name.into(), tool_callback);
334        self
335    }
336
337    /// Register a custom callback with its associated Tool definition. The Tool will be
338    /// automatically added to requests when tool callbacks are active.
339    pub fn with_tool_callback_and_tool(
340        mut self,
341        name: impl Into<String>,
342        tool_callback: Arc<ToolCallback>,
343        tool: Tool,
344    ) -> Self {
345        let name = name.into();
346        self.tool_callbacks_with_tools.insert(
347            name,
348            ToolCallbackWithTool {
349                callback: tool_callback,
350                tool,
351            },
352        );
353        self
354    }
355
356    /// Configure MCP client to connect to external MCP servers.
357    pub fn with_mcp_client(mut self, config: McpClientConfig) -> Self {
358        self.mcp_client_config = Some(config);
359        self
360    }
361
362    pub async fn build(self) -> Arc<MistralRs> {
363        MistralRs::new(self).await
364    }
365}
366
367impl Drop for MistralRs {
368    fn drop(&mut self) {
369        // Terminate all engines
370        if let Ok(engines) = self.engines.read() {
371            for (_, engine) in engines.iter() {
372                // Use try_send instead of blocking_send to avoid runtime panics
373                let _ = engine.sender.try_send(Request::Terminate);
374            }
375        }
376    }
377}
378
379impl MistralRs {
380    /// Create an engine instance with the given configuration
381    fn create_engine_instance(
382        pipeline: Arc<tokio::sync::Mutex<dyn Pipeline>>,
383        method: SchedulerConfig,
384        config: EngineConfig,
385        reboot_state: RebootState,
386    ) -> Result<EngineInstance, String> {
387        let (tx, rx) = channel(10_000);
388
389        let pipeline_guard = pipeline.try_lock().unwrap();
390        let category = pipeline_guard.category();
391        let metadata = pipeline_guard.get_metadata();
392        let kind = metadata.kind.clone();
393        let device = pipeline_guard.device();
394        let modalities = metadata.modalities.clone();
395        let max_seq_len = match &category {
396            ModelCategory::Diffusion | ModelCategory::Speech => None,
397            _ => Some(metadata.max_seq_len),
398        };
399        drop(pipeline_guard);
400
401        info!("Pipeline input modalities are {:?}", &modalities.input);
402        info!("Pipeline output modalities are {:?}", &modalities.output);
403
404        let mistralrs_config = MistralRsConfig {
405            kind,
406            device,
407            category: category.clone(),
408            modalities,
409            max_seq_len,
410        };
411
412        let tx_for_engine = tx.clone();
413        let engine_handler = thread::spawn(move || {
414            #[cfg(feature = "metal")]
415            objc::rc::autoreleasepool(move || {
416                let rt = Runtime::new().unwrap();
417                rt.block_on(async move {
418                    let engine = Engine::new(
419                        tx_for_engine,
420                        rx,
421                        pipeline,
422                        method,
423                        config.no_kv_cache,
424                        config.no_prefix_cache,
425                        config.prefix_cache_n,
426                        config.disable_eos_stop,
427                        config.throughput_logging_enabled,
428                        config.search_embedding_model,
429                        config.search_callback.clone(),
430                        config.tool_callbacks.clone(),
431                        config.tool_callbacks_with_tools.clone(),
432                    )
433                    .expect("Engine creation failed.");
434                    Arc::new(engine).run().await;
435                })
436            });
437
438            #[cfg(not(feature = "metal"))]
439            {
440                let rt = Runtime::new().unwrap();
441                rt.block_on(async move {
442                    let engine = Engine::new(
443                        tx_for_engine,
444                        rx,
445                        pipeline,
446                        method,
447                        config.no_kv_cache,
448                        config.no_prefix_cache,
449                        config.prefix_cache_n,
450                        config.disable_eos_stop,
451                        config.throughput_logging_enabled,
452                        config.search_embedding_model,
453                        config.search_callback.clone(),
454                        config.tool_callbacks.clone(),
455                        config.tool_callbacks_with_tools.clone(),
456                    )
457                    .expect("Engine creation failed.");
458                    Arc::new(engine).run().await;
459                })
460            }
461        });
462
463        Ok(EngineInstance {
464            sender: tx,
465            engine_handler,
466            reboot_state,
467            config: mistralrs_config,
468            category,
469        })
470    }
471
472    async fn new(config: MistralRsBuilder) -> Arc<Self> {
473        let MistralRsBuilder {
474            pipeline,
475            method,
476            log,
477            no_kv_cache,
478            no_prefix_cache,
479            prefix_cache_n,
480            disable_eos_stop,
481            throughput_logging_enabled,
482            search_embedding_model,
483            search_callback,
484            tool_callbacks,
485            mut tool_callbacks_with_tools,
486            mcp_client_config,
487        } = config;
488
489        mistralrs_quant::cublaslt::maybe_init_cublas_lt_wrapper(
490            get_mut_arcmutex!(pipeline).device(),
491        );
492
493        // For hybrid models (Mamba-Attention), force batch_size=1 to prevent state bleeding
494        // Mamba's stateful nature makes batched inference complex; this ensures correctness
495        let method = if get_mut_arcmutex!(pipeline).cache().is_hybrid() {
496            info!(
497                "Hybrid model detected (Mamba-Attention), enforcing batch_size=1 for correctness"
498            );
499            SchedulerConfig::DefaultScheduler {
500                method: DefaultSchedulerMethod::Fixed(NonZeroUsize::new(1).unwrap()),
501            }
502        } else {
503            method
504        };
505
506        let no_kv_cache = no_kv_cache.unwrap_or(false);
507        let no_prefix_cache = no_prefix_cache.unwrap_or(false);
508        let prefix_cache_n = prefix_cache_n.unwrap_or(16);
509        let disable_eos_stop = disable_eos_stop.unwrap_or(false);
510
511        // Initialize MCP client if configured
512        if let Some(config) = &mcp_client_config {
513            let mut mcp_client = McpClient::new(config.clone());
514            let total_servers = config.servers.len();
515
516            match mcp_client.initialize().await {
517                Ok(()) => {
518                    let mcp_callbacks_with_tools = mcp_client.get_tool_callbacks_with_tools();
519                    let tools_count = mcp_callbacks_with_tools.len();
520
521                    // Merge MCP tool callbacks with tools into the new collection
522                    for (name, callback_with_tool) in mcp_callbacks_with_tools {
523                        tool_callbacks_with_tools.insert(name.clone(), callback_with_tool.clone());
524                    }
525
526                    if tools_count == 0 {
527                        warn!(
528                            "MCP client initialized but no tools were registered from {} servers",
529                            total_servers
530                        );
531                    } else {
532                        info!(
533                            "MCP client initialized successfully with {} tools from {} servers",
534                            tools_count, total_servers
535                        );
536                    }
537                }
538                Err(e) => {
539                    warn!(
540                        "Failed to initialize MCP client with {} configured servers: {}",
541                        total_servers, e
542                    );
543                    warn!("Continuing without MCP functionality. Check your MCP configuration and server availability.");
544                }
545            }
546        }
547
548        let reboot_state = RebootState {
549            pipeline: pipeline.clone(),
550            method: method.clone(),
551            no_kv_cache,
552            no_prefix_cache,
553            prefix_cache_n,
554            disable_eos_stop,
555            throughput_logging_enabled,
556            search_embedding_model,
557            search_callback: search_callback.clone(),
558            tool_callbacks: tool_callbacks.clone(),
559            tool_callbacks_with_tools: tool_callbacks_with_tools.clone(),
560            mcp_client_config: mcp_client_config.clone(),
561        };
562
563        // Create the engine configuration
564        let engine_config = EngineConfig {
565            no_kv_cache,
566            no_prefix_cache,
567            prefix_cache_n,
568            disable_eos_stop,
569            throughput_logging_enabled,
570            search_embedding_model,
571            search_callback,
572            tool_callbacks,
573            tool_callbacks_with_tools,
574        };
575
576        // Create the engine instance
577        let engine_instance =
578            Self::create_engine_instance(pipeline.clone(), method, engine_config, reboot_state)
579                .expect("Failed to create engine instance");
580
581        let id = pipeline.try_lock().unwrap().name();
582
583        if distributed::is_daemon() {
584            let request_sender = engine_instance.sender.clone();
585
586            if cfg!(feature = "ring") {
587                // Ring daemon replicator
588                distributed::ring_daemon_replicator(request_sender);
589            } else {
590                // NCCL daemon replicator
591                distributed::nccl_daemon_replicator(request_sender);
592            }
593
594            #[allow(clippy::empty_loop)]
595            loop {}
596        }
597
598        // Determine if the current runtime is multi-threaded, as blocking operations are not allowed in single-threaded mode
599        let is_multi_threaded = tokio::runtime::Handle::try_current()
600            .is_ok_and(|h| h.runtime_flavor() != tokio::runtime::RuntimeFlavor::CurrentThread);
601
602        // Do a dummy run
603        if !distributed::is_daemon()
604            && is_multi_threaded
605            && matches!(
606                engine_instance.category,
607                ModelCategory::Text | ModelCategory::Vision { .. }
608            )
609        {
610            let clone_sender = engine_instance.sender.clone();
611            tokio::task::block_in_place(|| {
612                let (tx, mut rx) = channel(1);
613                let req = Request::Normal(Box::new(NormalRequest {
614                    id: 0,
615                    messages: RequestMessage::Completion {
616                        text: "hello".to_string(),
617                        echo_prompt: false,
618                        best_of: None,
619                    },
620                    sampling_params: SamplingParams {
621                        max_len: Some(1),
622                        ..SamplingParams::deterministic()
623                    },
624                    response: tx,
625                    return_logprobs: false,
626                    is_streaming: false,
627                    constraint: Constraint::None,
628                    suffix: None,
629                    tool_choice: None,
630                    tools: None,
631                    logits_processors: None,
632                    return_raw_logits: false,
633                    web_search_options: None,
634                    model_id: None,
635                    truncate_sequence: false,
636                }));
637                info!("Beginning dummy run.");
638                let start = Instant::now();
639                clone_sender.blocking_send(req).unwrap();
640
641                // Drain all responses from the channel until it's closed
642                let mut received_any = false;
643                while let Some(_resp) = rx.blocking_recv() {
644                    received_any = true;
645                }
646
647                if received_any {
648                    let end = Instant::now();
649                    info!(
650                        "Dummy run completed in {}s.",
651                        end.duration_since(start).as_secs_f64()
652                    );
653                } else {
654                    warn!("Dummy run failed!");
655                }
656            });
657        }
658
659        // Create engines map with the first engine
660        let mut engines = HashMap::new();
661        engines.insert(id.clone(), engine_instance);
662
663        Arc::new(Self {
664            engines: RwLock::new(engines),
665            default_engine_id: RwLock::new(Some(id.clone())),
666            log,
667            id,
668            creation_time: SystemTime::now()
669                .duration_since(UNIX_EPOCH)
670                .expect("Time travel has occurred!")
671                .as_secs(),
672            next_request_id: Mutex::new(RefCell::new(1)),
673        })
674    }
675
676    /// Attempts to reboot a specific engine by model_id
677    fn reboot_engine(&self, model_id: &str) -> Result<(), MistralRsError> {
678        let mut engines = self.engines.write().map_err(|_| {
679            tracing::warn!("Couldn't get write lock on engines during reboot attempt");
680            MistralRsError::EnginePoisoned
681        })?;
682
683        if let Some(engine_instance) = engines.get(model_id) {
684            if !engine_instance.engine_handler.is_finished() {
685                tracing::info!("Engine {} already running, returning ok", model_id);
686                return Ok(());
687            }
688
689            let reboot_state = engine_instance.reboot_state.clone();
690            let engine_config = EngineConfig {
691                no_kv_cache: reboot_state.no_kv_cache,
692                no_prefix_cache: reboot_state.no_prefix_cache,
693                prefix_cache_n: reboot_state.prefix_cache_n,
694                disable_eos_stop: reboot_state.disable_eos_stop,
695                throughput_logging_enabled: reboot_state.throughput_logging_enabled,
696                search_embedding_model: reboot_state.search_embedding_model,
697                search_callback: reboot_state.search_callback.clone(),
698                tool_callbacks: reboot_state.tool_callbacks.clone(),
699                tool_callbacks_with_tools: reboot_state.tool_callbacks_with_tools.clone(),
700            };
701            let new_engine_instance = Self::create_engine_instance(
702                reboot_state.pipeline.clone(),
703                reboot_state.method.clone(),
704                engine_config,
705                reboot_state,
706            )
707            .map_err(|e| {
708                tracing::error!("Failed to create new engine instance: {}", e);
709                MistralRsError::EnginePoisoned
710            })?;
711
712            engines.insert(model_id.to_string(), new_engine_instance);
713            tracing::info!("Successfully rebooted engine {}", model_id);
714            Ok(())
715        } else {
716            Err(MistralRsError::EnginePoisoned)
717        }
718    }
719
720    fn engine_dead(&self, model_id: &str) -> Result<bool, MistralRsError> {
721        let engines = self.engines.read().map_err(|_| {
722            tracing::warn!("Couldn't get read lock on engines!");
723            MistralRsError::EnginePoisoned
724        })?;
725
726        if let Some(engine_instance) = engines.get(model_id) {
727            Ok(engine_instance.engine_handler.is_finished())
728        } else {
729            Err(MistralRsError::EnginePoisoned)
730        }
731    }
732
733    /// Get sender for a specific model. If model_id is None, uses default engine.
734    pub fn get_sender(&self, model_id: Option<&str>) -> Result<Sender<Request>, MistralRsError> {
735        let resolved_model_id = match model_id {
736            Some(id) => id.to_string(),
737            None => {
738                let default_lock = self
739                    .default_engine_id
740                    .read()
741                    .map_err(|_| MistralRsError::SenderPoisoned)?;
742                default_lock
743                    .as_ref()
744                    .ok_or(MistralRsError::EnginePoisoned)?
745                    .clone()
746            }
747        };
748
749        if self.engine_dead(&resolved_model_id)? {
750            tracing::warn!("Engine {} is dead, rebooting", resolved_model_id);
751            self.reboot_engine(&resolved_model_id)?
752        }
753
754        let engines = self
755            .engines
756            .read()
757            .map_err(|_| MistralRsError::SenderPoisoned)?;
758        if let Some(engine_instance) = engines.get(&resolved_model_id) {
759            Ok(engine_instance.sender.clone())
760        } else {
761            Err(MistralRsError::EnginePoisoned)
762        }
763    }
764
765    pub fn get_id(&self) -> String {
766        self.id.clone()
767    }
768
769    pub fn get_creation_time(&self) -> u64 {
770        self.creation_time
771    }
772
773    /// Get model category for a specific model. If model_id is None, uses default engine.
774    pub fn get_model_category(
775        &self,
776        model_id: Option<&str>,
777    ) -> Result<ModelCategory, MistralRsError> {
778        let resolved_model_id = match model_id {
779            Some(id) => id.to_string(),
780            None => {
781                let default_lock = self
782                    .default_engine_id
783                    .read()
784                    .map_err(|_| MistralRsError::SenderPoisoned)?;
785                default_lock
786                    .as_ref()
787                    .ok_or(MistralRsError::EnginePoisoned)?
788                    .clone()
789            }
790        };
791
792        let engines = self
793            .engines
794            .read()
795            .map_err(|_| MistralRsError::SenderPoisoned)?;
796        if let Some(engine_instance) = engines.get(&resolved_model_id) {
797            Ok(engine_instance.category.clone())
798        } else {
799            Err(MistralRsError::EnginePoisoned)
800        }
801    }
802
803    /// Get the maximum supported sequence length for a model, if applicable.
804    pub fn max_sequence_length(
805        &self,
806        model_id: Option<&str>,
807    ) -> Result<Option<usize>, MistralRsError> {
808        let resolved_model_id = match model_id {
809            Some(id) => id.to_string(),
810            None => {
811                let default_lock = self
812                    .default_engine_id
813                    .read()
814                    .map_err(|_| MistralRsError::SenderPoisoned)?;
815                default_lock
816                    .as_ref()
817                    .ok_or(MistralRsError::EnginePoisoned)?
818                    .clone()
819            }
820        };
821
822        let engines = self
823            .engines
824            .read()
825            .map_err(|_| MistralRsError::SenderPoisoned)?;
826        if let Some(engine_instance) = engines.get(&resolved_model_id) {
827            Ok(engine_instance.config.max_seq_len)
828        } else {
829            Err(MistralRsError::EnginePoisoned)
830        }
831    }
832
833    pub fn next_request_id(&self) -> usize {
834        let l = self.next_request_id.lock().unwrap();
835        let last = &mut *l.borrow_mut();
836        let last_v = *last;
837        *last += 1;
838        last_v
839    }
840
841    /// Add a new model engine to the MistralRs instance
842    pub async fn add_model(
843        &self,
844        model_id: String,
845        pipeline: Arc<tokio::sync::Mutex<dyn Pipeline>>,
846        method: SchedulerConfig,
847        config: AddModelConfig,
848    ) -> Result<(), String> {
849        // For hybrid models (Mamba-Attention), force batch_size=1 to prevent state bleeding
850        let method = if pipeline.try_lock().unwrap().cache().is_hybrid() {
851            info!(
852                "Hybrid model detected (Mamba-Attention), enforcing batch_size=1 for correctness"
853            );
854            SchedulerConfig::DefaultScheduler {
855                method: DefaultSchedulerMethod::Fixed(NonZeroUsize::new(1).unwrap()),
856            }
857        } else {
858            method
859        };
860
861        let reboot_state = RebootState {
862            pipeline: pipeline.clone(),
863            method: method.clone(),
864            no_kv_cache: config.engine_config.no_kv_cache,
865            no_prefix_cache: config.engine_config.no_prefix_cache,
866            prefix_cache_n: config.engine_config.prefix_cache_n,
867            disable_eos_stop: config.engine_config.disable_eos_stop,
868            throughput_logging_enabled: config.engine_config.throughput_logging_enabled,
869            search_embedding_model: config.engine_config.search_embedding_model,
870            search_callback: config.engine_config.search_callback.clone(),
871            tool_callbacks: config.engine_config.tool_callbacks.clone(),
872            tool_callbacks_with_tools: config.engine_config.tool_callbacks_with_tools.clone(),
873            mcp_client_config: config.mcp_client_config.clone(),
874        };
875
876        let engine_instance =
877            Self::create_engine_instance(pipeline, method, config.engine_config, reboot_state)?;
878
879        let mut engines = self
880            .engines
881            .write()
882            .map_err(|_| "Failed to acquire write lock on engines")?;
883        engines.insert(model_id.clone(), engine_instance);
884
885        // If this is the first model, set it as default
886        if engines.len() == 1 {
887            let mut default_lock = self
888                .default_engine_id
889                .write()
890                .map_err(|_| "Failed to acquire write lock on default_engine_id")?;
891            *default_lock = Some(model_id.clone());
892        }
893
894        Ok(())
895    }
896
897    /// Remove a model engine from the MistralRs instance
898    pub fn remove_model(&self, model_id: &str) -> Result<(), String> {
899        let mut engines = self
900            .engines
901            .write()
902            .map_err(|_| "Failed to acquire write lock on engines")?;
903
904        if engines.len() <= 1 {
905            return Err("Cannot remove the last model from MistralRs".to_string());
906        }
907
908        if let Some(engine_instance) = engines.remove(model_id) {
909            // Send terminate signal to the engine
910            let _ = engine_instance.sender.blocking_send(Request::Terminate);
911
912            // If this was the default engine, set a new default
913            let mut default_lock = self
914                .default_engine_id
915                .write()
916                .map_err(|_| "Failed to acquire write lock on default_engine_id")?;
917            if let Some(ref default_id) = *default_lock {
918                if default_id == model_id {
919                    // Set the first available engine as the new default
920                    *default_lock = engines.keys().next().cloned();
921                }
922            }
923
924            Ok(())
925        } else {
926            Err(format!("Model {model_id} not found"))
927        }
928    }
929
930    /// List all available model IDs
931    pub fn list_models(&self) -> Result<Vec<String>, String> {
932        let engines = self
933            .engines
934            .read()
935            .map_err(|_| "Failed to acquire read lock on engines")?;
936        Ok(engines.keys().cloned().collect())
937    }
938
939    /// Get the current default model ID
940    pub fn get_default_model_id(&self) -> Result<Option<String>, String> {
941        let default_lock = self
942            .default_engine_id
943            .read()
944            .map_err(|_| "Failed to acquire read lock on default_engine_id")?;
945        Ok(default_lock.clone())
946    }
947
948    /// Set the default model ID
949    pub fn set_default_model_id(&self, model_id: &str) -> Result<(), String> {
950        let engines = self
951            .engines
952            .read()
953            .map_err(|_| "Failed to acquire read lock on engines")?;
954        if !engines.contains_key(model_id) {
955            return Err(format!("Model {model_id} not found"));
956        }
957        drop(engines);
958
959        let mut default_lock = self
960            .default_engine_id
961            .write()
962            .map_err(|_| "Failed to acquire write lock on default_engine_id")?;
963        *default_lock = Some(model_id.to_string());
964
965        Ok(())
966    }
967
968    /// Dispatch a request to the appropriate engine based on the model_id in the request
969    pub fn send_request(&self, mut request: Request) -> Result<(), MistralRsError> {
970        let model_id = match &mut request {
971            Request::Normal(normal_req) => normal_req.model_id.as_deref(),
972            _ => None, // Other request types don't specify model_id
973        };
974
975        let sender = self.get_sender(model_id)?;
976        sender
977            .blocking_send(request)
978            .map_err(|_| MistralRsError::SenderPoisoned)
979    }
980
981    pub fn maybe_log_request(this: Arc<Self>, repr: String) {
982        if let Some(file) = &this.log {
983            let mut f = OpenOptions::new()
984                .append(true)
985                .create(true) // Optionally create the file if it doesn't already exist
986                .open(file)
987                .expect("Unable to open file");
988            let time = chrono::offset::Local::now();
989            f.write_all(format!("Request at {time}: {repr}\n\n").as_bytes())
990                .expect("Unable to write data");
991        }
992    }
993
994    pub fn maybe_log_response<T: Serialize>(this: Arc<Self>, resp: &T) {
995        if let Some(file) = &this.log {
996            let mut f = OpenOptions::new()
997                .append(true)
998                .create(true) // Optionally create the file if it doesn't already exist
999                .open(file)
1000                .expect("Unable to open file");
1001            let time = chrono::offset::Local::now();
1002            let repr = serde_json::to_string(resp).expect("Serialization of response failed.");
1003            f.write_all(format!("Response at {time}: {repr}\n\n").as_bytes())
1004                .expect("Unable to write data");
1005        }
1006    }
1007
1008    pub fn maybe_log_error(this: Arc<Self>, err: &dyn Error) {
1009        if let Some(file) = &this.log {
1010            let mut f = OpenOptions::new()
1011                .append(true)
1012                .create(true) // Optionally create the file if it doesn't already exist
1013                .open(file)
1014                .expect("Unable to open file");
1015            let time = chrono::offset::Local::now();
1016            f.write_all(format!("Error response at {time}: {err}\n\n").as_bytes())
1017                .expect("Unable to write data");
1018        }
1019    }
1020
1021    /// Get the number of tools available for a specific model (including MCP tools)
1022    pub fn get_tools_count(&self, model_id: Option<&str>) -> Result<usize, String> {
1023        let resolved_model_id = match model_id {
1024            Some(id) => id.to_string(),
1025            None => {
1026                let default_lock = self
1027                    .default_engine_id
1028                    .read()
1029                    .map_err(|_| "Failed to acquire read lock")?;
1030                default_lock
1031                    .as_ref()
1032                    .ok_or("No default engine set")?
1033                    .clone()
1034            }
1035        };
1036
1037        let engines = self
1038            .engines
1039            .read()
1040            .map_err(|_| "Failed to acquire read lock on engines")?;
1041        if let Some(engine_instance) = engines.get(&resolved_model_id) {
1042            Ok(engine_instance.reboot_state.tool_callbacks_with_tools.len())
1043        } else {
1044            Err(format!("Model {resolved_model_id} not found"))
1045        }
1046    }
1047
1048    /// Check if MCP client is configured for a specific model
1049    pub fn has_mcp_client(&self, model_id: Option<&str>) -> Result<bool, String> {
1050        let resolved_model_id = match model_id {
1051            Some(id) => id.to_string(),
1052            None => {
1053                let default_lock = self
1054                    .default_engine_id
1055                    .read()
1056                    .map_err(|_| "Failed to acquire read lock")?;
1057                default_lock
1058                    .as_ref()
1059                    .ok_or("No default engine set")?
1060                    .clone()
1061            }
1062        };
1063
1064        let engines = self
1065            .engines
1066            .read()
1067            .map_err(|_| "Failed to acquire read lock on engines")?;
1068        if let Some(engine_instance) = engines.get(&resolved_model_id) {
1069            Ok(engine_instance.reboot_state.mcp_client_config.is_some())
1070        } else {
1071            Err(format!("Model {resolved_model_id} not found"))
1072        }
1073    }
1074
1075    /// Get config for a specific model
1076    pub fn config(&self, model_id: Option<&str>) -> Result<MistralRsConfig, String> {
1077        let resolved_model_id = match model_id {
1078            Some(id) => id.to_string(),
1079            None => {
1080                let default_lock = self
1081                    .default_engine_id
1082                    .read()
1083                    .map_err(|_| "Failed to acquire read lock")?;
1084                default_lock
1085                    .as_ref()
1086                    .ok_or("No default engine set")?
1087                    .clone()
1088            }
1089        };
1090
1091        let engines = self
1092            .engines
1093            .read()
1094            .map_err(|_| "Failed to acquire read lock on engines")?;
1095        if let Some(engine_instance) = engines.get(&resolved_model_id) {
1096            Ok(engine_instance.config.clone())
1097        } else {
1098            Err(format!("Model {resolved_model_id} not found"))
1099        }
1100    }
1101}