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::sanitize_std_command_environment;
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            let mut command = std::process::Command::new(&lms_for_task);
249            sanitize_std_command_environment(&mut command, &[]);
250            command
251                .args(["get", "--yes", &model_for_task])
252                .stdout(std::process::Stdio::inherit())
253                .stderr(std::process::Stdio::null())
254                .status()
255        })
256        .await
257        .map_err(|e| io::Error::other(format!("Model download task panicked: {e}")))?
258        .map_err(|e| io::Error::other(format!("Failed to execute '{lms} get --yes {model}': {e}")))?;
259
260        if !status.success() {
261            return Err(io::Error::other(format!(
262                "Model download failed with exit code: {}",
263                status.code().unwrap_or(-1)
264            )));
265        }
266
267        tracing::info!("Successfully downloaded model '{model}'");
268        Ok(())
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    use crate::providers::test_support::start_mock_server_or_skip;
277
278    #[test]
279    fn test_find_lms() {
280        let result = LMStudioClient::find_lms();
281        match result {
282            Ok(_) => {
283                // lms was found in PATH - that's fine
284            }
285            Err(e) => {
286                // Expected error when LM Studio not installed
287                assert!(e.to_string().contains("LM Studio not found"));
288            }
289        }
290    }
291
292    #[test]
293    fn test_find_lms_with_mock_home() {
294        // Test fallback path construction without touching env vars
295        #[cfg(unix)]
296        {
297            let result = LMStudioClient::find_lms_with_home_dir(Some("/test/home"));
298            if let Err(e) = result {
299                assert!(e.to_string().contains("LM Studio not found"));
300            }
301        }
302        #[cfg(windows)]
303        {
304            let result = LMStudioClient::find_lms_with_home_dir(Some("C:\\test\\home"));
305            if let Err(e) = result {
306                assert!(e.to_string().contains("LM Studio not found"));
307            }
308        }
309    }
310
311    #[tokio::test]
312    async fn test_fetch_models_happy_path() {
313        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
314            return;
315        }
316
317        let Some(server) = start_mock_server_or_skip().await else {
318            return;
319        };
320        wiremock::Mock::given(wiremock::matchers::method("GET"))
321            .and(wiremock::matchers::path("/v1/models"))
322            .respond_with(
323                wiremock::ResponseTemplate::new(200).set_body_raw(
324                    serde_json::json!({
325                        "data": [
326                            {"id": "openai/gpt-oss-20b"},
327                        ]
328                    })
329                    .to_string(),
330                    "application/json",
331                ),
332            )
333            .mount(&server)
334            .await;
335
336        let client = LMStudioClient::try_from_base_url(&server.uri()).await;
337        assert!(client.is_ok());
338
339        let client = client.unwrap();
340        let models = client.fetch_models().await.expect("fetch models");
341        assert!(models.contains(&"openai/gpt-oss-20b".to_string()));
342    }
343
344    #[tokio::test]
345    async fn test_fetch_models_native_api() {
346        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
347            return;
348        }
349
350        let Some(server) = start_mock_server_or_skip().await else {
351            return;
352        };
353        wiremock::Mock::given(wiremock::matchers::method("GET"))
354            .and(wiremock::matchers::path("/api/v0/models"))
355            .respond_with(
356                wiremock::ResponseTemplate::new(200).set_body_raw(
357                    serde_json::json!({
358                        "data": [
359                            {"id": "lmstudio-community/meta-llama-3.1-8b-instruct"},
360                        ]
361                    })
362                    .to_string(),
363                    "application/json",
364                ),
365            )
366            .mount(&server)
367            .await;
368
369        let client = LMStudioClient::try_from_base_url_with_api_version(&server.uri(), true).await;
370        assert!(client.is_ok());
371
372        let client = client.unwrap();
373        let models = client.fetch_models().await.expect("fetch models");
374        assert!(models.contains(&"lmstudio-community/meta-llama-3.1-8b-instruct".to_string()));
375    }
376
377    #[tokio::test]
378    async fn test_fetch_models_no_data_array() {
379        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
380            return;
381        }
382
383        let Some(server) = start_mock_server_or_skip().await else {
384            return;
385        };
386        wiremock::Mock::given(wiremock::matchers::method("GET"))
387            .and(wiremock::matchers::path("/v1/models"))
388            .respond_with(
389                wiremock::ResponseTemplate::new(200)
390                    .set_body_raw(serde_json::json!({}).to_string(), "application/json"),
391            )
392            .mount(&server)
393            .await;
394
395        let client = LMStudioClient::try_from_base_url(&server.uri()).await;
396        let client = client.unwrap();
397        let result = client.fetch_models().await;
398
399        assert!(result.is_err());
400        assert!(result.unwrap_err().to_string().contains("No 'data' array in response"));
401    }
402
403    #[tokio::test]
404    async fn test_check_server_happy_path() {
405        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
406            return;
407        }
408
409        let Some(server) = start_mock_server_or_skip().await else {
410            return;
411        };
412        wiremock::Mock::given(wiremock::matchers::method("GET"))
413            .and(wiremock::matchers::path("/v1/models"))
414            .respond_with(wiremock::ResponseTemplate::new(200))
415            .mount(&server)
416            .await;
417
418        let result = LMStudioClient::try_from_base_url(&server.uri()).await;
419        result.unwrap();
420    }
421
422    #[tokio::test]
423    async fn test_check_server_error() {
424        if std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() {
425            return;
426        }
427
428        let Some(server) = start_mock_server_or_skip().await else {
429            return;
430        };
431        wiremock::Mock::given(wiremock::matchers::method("GET"))
432            .and(wiremock::matchers::path("/v1/models"))
433            .respond_with(wiremock::ResponseTemplate::new(404))
434            .mount(&server)
435            .await;
436
437        let result = LMStudioClient::try_from_base_url(&server.uri()).await;
438        assert!(result.is_err());
439        assert!(result.unwrap_err().to_string().contains("Server returned error: 404"));
440    }
441}