Skip to main content

vtcode_llm/providers/lmstudio/
client.rs

1/// High-level LM Studio client for server interaction and model management.
2///
3/// Supports both LM Studio native REST API (`/api/v0/*`) and OpenAI-compatible
4/// endpoints (`/v1/*`). The native API provides enhanced features like model
5/// management (load/unload), richer model metadata, and TTL-based auto-evict.
6///
7/// See: https://lmstudio.ai/docs/developer
8use std::io;
9use std::path::Path;
10
11use serde_json::Value as JsonValue;
12
13use crate::process_env::provider_std_command;
14
15pub(crate) const LMSTUDIO_CONNECTION_ERROR: &str =
16    "LM Studio is not responding. Install from https://lmstudio.ai/download and run 'lms server start'.";
17
18/// Client for interacting with a local LM Studio instance.
19///
20/// Supports both native REST API (`/api/v0/*`) and OpenAI-compatible endpoints (`/v1/*`).
21#[derive(Clone, Debug)]
22pub struct LMStudioClient {
23    client: reqwest::Client,
24    base_url: String,
25    /// Use native REST API endpoints (default: false, uses OpenAI-compatible endpoints)
26    use_native_api: bool,
27}
28
29impl LMStudioClient {
30    /// Create a client from a base URL and verify the server is reachable.
31    async fn try_from_base_url(base_url: &str) -> io::Result<Self> {
32        Self::try_from_base_url_with_api_version(base_url, false).await
33    }
34
35    /// Create a client with explicit API version selection.
36    ///
37    /// - `use_native_api = false`: Use OpenAI-compatible endpoints at `/v1/*` (default)
38    /// - `use_native_api = true`: Use native REST API at `/api/v0/*`
39    async fn try_from_base_url_with_api_version(base_url: &str, use_native_api: bool) -> io::Result<Self> {
40        // A connect-only timeout leaves `check_server`/`fetch_models` unbounded
41        // when LM Studio accepts the socket but stalls; use the installed
42        // request budget so model discovery cannot hang the picker.
43        let client = vtcode_commons::http::create_default_client();
44
45        let instance = Self {
46            client,
47            base_url: base_url.to_string(),
48            use_native_api,
49        };
50
51        instance.check_server().await?;
52        Ok(instance)
53    }
54
55    /// Get the models endpoint URL based on API version.
56    fn models_endpoint(&self) -> String {
57        let base = self.base_url.trim_end_matches('/');
58        if self.use_native_api {
59            format!("{base}/api/v0/models")
60        } else {
61            format!("{base}/v1/models")
62        }
63    }
64
65    /// Verify that the server is reachable.
66    async fn check_server(&self) -> io::Result<()> {
67        let url = self.models_endpoint();
68        let response = self.client.get(&url).send().await;
69
70        if let Ok(resp) = response {
71            if resp.status().is_success() {
72                Ok(())
73            } else {
74                Err(io::Error::other(format!("Server returned error: {} {LMSTUDIO_CONNECTION_ERROR}", resp.status())))
75            }
76        } else {
77            Err(io::Error::other(LMSTUDIO_CONNECTION_ERROR))
78        }
79    }
80
81    /// Fetch the list of model IDs available on the server.
82    async fn fetch_models(&self) -> io::Result<Vec<String>> {
83        let url = self.models_endpoint();
84        let response = self
85            .client
86            .get(&url)
87            .send()
88            .await
89            .map_err(|e| io::Error::other(format!("Request failed: {e}")))?;
90
91        if response.status().is_success() {
92            let json: JsonValue = response
93                .json()
94                .await
95                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("JSON parse error: {e}")))?;
96
97            let models = json["data"]
98                .as_array()
99                .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "No 'data' array in response"))?
100                .iter()
101                .filter_map(|model| model["id"].as_str())
102                .map(ToString::to_string)
103                .collect();
104
105            Ok(models)
106        } else {
107            Err(io::Error::other(format!("Failed to fetch models: {}", response.status())))
108        }
109    }
110
111    /// Load a model into memory (pre-loads for faster inference).
112    ///
113    /// Uses native REST API `/api/v0/models/load` when `use_native_api` is true,
114    /// otherwise sends a minimal request via `/v1/chat/completions`.
115    pub async fn load_model(&self, model: &str) -> io::Result<()> {
116        if self.use_native_api {
117            let url = format!("{}/api/v0/models/load", self.base_url.trim_end_matches('/'));
118            let request_body = serde_json::json!({
119                "model": model
120            });
121
122            let response = self
123                .client
124                .post(&url)
125                .header("Content-Type", "application/json")
126                .json(&request_body)
127                .send()
128                .await
129                .map_err(|e| io::Error::other(format!("Request failed: {e}")))?;
130
131            if response.status().is_success() {
132                tracing::info!("Successfully loaded model '{model}' via native API");
133                Ok(())
134            } else {
135                Err(io::Error::other(format!("Failed to load model: {}", response.status())))
136            }
137        } else {
138            // Use OpenAI-compatible endpoint with minimal chat completion
139            let url = format!("{}/v1/chat/completions", self.base_url.trim_end_matches('/'));
140            let request_body = serde_json::json!({
141                "model": model,
142                "messages": [{"role": "user", "content": "hi"}],
143                "max_tokens": 1
144            });
145
146            let response = self
147                .client
148                .post(&url)
149                .header("Content-Type", "application/json")
150                .json(&request_body)
151                .send()
152                .await
153                .map_err(|e| io::Error::other(format!("Request failed: {e}")))?;
154
155            if response.status().is_success() {
156                tracing::info!("Successfully loaded model '{model}'");
157                Ok(())
158            } else {
159                Err(io::Error::other(format!("Failed to load model: {}", response.status())))
160            }
161        }
162    }
163
164    /// Unload a model from memory (native REST API only).
165    ///
166    /// This endpoint requires `use_native_api = true`.
167    pub async fn unload_model(&self, model: &str) -> io::Result<()> {
168        if !self.use_native_api {
169            return Err(io::Error::other("Model unload requires native API (use_native_api = true)"));
170        }
171
172        let url = format!("{}/api/v0/models/unload", self.base_url.trim_end_matches('/'));
173        let request_body = serde_json::json!({
174            "model": model
175        });
176
177        let response = self
178            .client
179            .post(&url)
180            .header("Content-Type", "application/json")
181            .json(&request_body)
182            .send()
183            .await
184            .map_err(|e| io::Error::other(format!("Request failed: {e}")))?;
185
186        if response.status().is_success() {
187            tracing::info!("Successfully unloaded model '{model}'");
188            Ok(())
189        } else {
190            Err(io::Error::other(format!("Failed to unload model: {}", response.status())))
191        }
192    }
193
194    /// Find the `lms` CLI tool, checking PATH and fallback locations.
195    fn find_lms() -> io::Result<String> {
196        Self::find_lms_with_home_dir(None)
197    }
198
199    /// Find `lms` CLI with an optional home directory override (for testing).
200    fn find_lms_with_home_dir(home_dir: Option<&str>) -> io::Result<String> {
201        // First try 'lms' in PATH
202        if which::which("lms").is_ok() {
203            return Ok("lms".to_string());
204        }
205
206        // Platform-specific fallback paths
207        let home = match home_dir {
208            Some(dir) => dir.to_string(),
209            None => {
210                #[cfg(unix)]
211                {
212                    std::env::var("HOME").unwrap_or_default()
213                }
214                #[cfg(windows)]
215                {
216                    std::env::var("USERPROFILE").unwrap_or_default()
217                }
218            }
219        };
220
221        #[cfg(unix)]
222        let fallback_path = format!("{home}/.lmstudio/bin/lms");
223        #[cfg(windows)]
224        let fallback_path = format!("{home}/.lmstudio/bin/lms.exe");
225
226        if Path::new(&fallback_path).exists() {
227            Ok(fallback_path)
228        } else {
229            Err(io::Error::new(
230                io::ErrorKind::NotFound,
231                "LM Studio not found. Please install LM Studio from https://lmstudio.ai/",
232            ))
233        }
234    }
235
236    /// Download a model using the `lms` CLI tool.
237    pub async fn download_model(&self, model: &str) -> io::Result<()> {
238        let lms = Self::find_lms()?;
239        tracing::info!(model, "downloading model");
240
241        // `Command::status()` blocks until the `lms get` subprocess exits; run
242        // it off the async executor so it cannot stall Tokio workers. See `# Blocking`
243        // docs in `src/agent/runloop/git.rs`.
244        let model = model.to_string();
245        let lms_for_task = lms.clone();
246        let model_for_task = model.clone();
247        let status = tokio::task::spawn_blocking(move || {
248            provider_std_command(&lms_for_task, None, &[])
249                .args(["get", "--yes", &model_for_task])
250                .stdout(std::process::Stdio::inherit())
251                .stderr(std::process::Stdio::null())
252                .status()
253        })
254        .await
255        .map_err(|e| io::Error::other(format!("Model download task panicked: {e}")))?
256        .map_err(|e| io::Error::other(format!("Failed to execute '{lms} get --yes {model}': {e}")))?;
257
258        if !status.success() {
259            return Err(io::Error::other(format!(
260                "Model download failed with exit code: {}",
261                status.code().unwrap_or(-1)
262            )));
263        }
264
265        tracing::info!("Successfully downloaded model '{model}'");
266        Ok(())
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    use crate::providers::test_support::start_mock_server_or_skip;
275
276    #[test]
277    fn test_find_lms() {
278        let result = LMStudioClient::find_lms();
279        match result {
280            Ok(_) => {
281                // lms was found in PATH - that's fine
282            }
283            Err(e) => {
284                // Expected error when LM Studio not installed
285                assert!(e.to_string().contains("LM Studio not found"));
286            }
287        }
288    }
289
290    #[test]
291    fn test_find_lms_with_mock_home() {
292        // Test fallback path construction without touching env vars
293        #[cfg(unix)]
294        {
295            let result = LMStudioClient::find_lms_with_home_dir(Some("/test/home"));
296            if let Err(e) = result {
297                assert!(e.to_string().contains("LM Studio not found"));
298            }
299        }
300        #[cfg(windows)]
301        {
302            let result = LMStudioClient::find_lms_with_home_dir(Some("C:\\test\\home"));
303            if let Err(e) = result {
304                assert!(e.to_string().contains("LM Studio not found"));
305            }
306        }
307    }
308
309    #[tokio::test]
310    async fn test_fetch_models_happy_path() {
311        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
312            return;
313        }
314
315        let Some(server) = start_mock_server_or_skip().await else {
316            return;
317        };
318        wiremock::Mock::given(wiremock::matchers::method("GET"))
319            .and(wiremock::matchers::path("/v1/models"))
320            .respond_with(
321                wiremock::ResponseTemplate::new(200).set_body_raw(
322                    serde_json::json!({
323                        "data": [
324                            {"id": "openai/gpt-oss-20b"},
325                        ]
326                    })
327                    .to_string(),
328                    "application/json",
329                ),
330            )
331            .mount(&server)
332            .await;
333
334        let client = LMStudioClient::try_from_base_url(&server.uri()).await;
335        assert!(client.is_ok());
336
337        let client = client.unwrap();
338        let models = client.fetch_models().await.expect("fetch models");
339        assert!(models.contains(&"openai/gpt-oss-20b".to_string()));
340    }
341
342    #[tokio::test]
343    async fn test_fetch_models_native_api() {
344        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
345            return;
346        }
347
348        let Some(server) = start_mock_server_or_skip().await else {
349            return;
350        };
351        wiremock::Mock::given(wiremock::matchers::method("GET"))
352            .and(wiremock::matchers::path("/api/v0/models"))
353            .respond_with(
354                wiremock::ResponseTemplate::new(200).set_body_raw(
355                    serde_json::json!({
356                        "data": [
357                            {"id": "lmstudio-community/meta-llama-3.1-8b-instruct"},
358                        ]
359                    })
360                    .to_string(),
361                    "application/json",
362                ),
363            )
364            .mount(&server)
365            .await;
366
367        let client = LMStudioClient::try_from_base_url_with_api_version(&server.uri(), true).await;
368        assert!(client.is_ok());
369
370        let client = client.unwrap();
371        let models = client.fetch_models().await.expect("fetch models");
372        assert!(models.contains(&"lmstudio-community/meta-llama-3.1-8b-instruct".to_string()));
373    }
374
375    #[tokio::test]
376    async fn test_fetch_models_no_data_array() {
377        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
378            return;
379        }
380
381        let Some(server) = start_mock_server_or_skip().await else {
382            return;
383        };
384        wiremock::Mock::given(wiremock::matchers::method("GET"))
385            .and(wiremock::matchers::path("/v1/models"))
386            .respond_with(
387                wiremock::ResponseTemplate::new(200)
388                    .set_body_raw(serde_json::json!({}).to_string(), "application/json"),
389            )
390            .mount(&server)
391            .await;
392
393        let client = LMStudioClient::try_from_base_url(&server.uri()).await;
394        let client = client.unwrap();
395        let result = client.fetch_models().await;
396
397        assert!(result.is_err());
398        assert!(result.unwrap_err().to_string().contains("No 'data' array in response"));
399    }
400
401    #[tokio::test]
402    async fn test_check_server_happy_path() {
403        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
404            return;
405        }
406
407        let Some(server) = start_mock_server_or_skip().await else {
408            return;
409        };
410        wiremock::Mock::given(wiremock::matchers::method("GET"))
411            .and(wiremock::matchers::path("/v1/models"))
412            .respond_with(wiremock::ResponseTemplate::new(200))
413            .mount(&server)
414            .await;
415
416        let result = LMStudioClient::try_from_base_url(&server.uri()).await;
417        result.unwrap();
418    }
419
420    #[tokio::test]
421    async fn test_check_server_error() {
422        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
423            return;
424        }
425
426        let Some(server) = start_mock_server_or_skip().await else {
427            return;
428        };
429        wiremock::Mock::given(wiremock::matchers::method("GET"))
430            .and(wiremock::matchers::path("/v1/models"))
431            .respond_with(wiremock::ResponseTemplate::new(404))
432            .mount(&server)
433            .await;
434
435        let result = LMStudioClient::try_from_base_url(&server.uri()).await;
436        assert!(result.is_err());
437        assert!(result.unwrap_err().to_string().contains("Server returned error: 404"));
438    }
439}