feat: implement service management API for VLM control

- Add /api/v1/mbe/health endpoint for status checks
- Add /api/v2/service/start to start llama-server
- Add /api/v2/service/stop to stop llama-server
- Use TCP connection test for port detection (more reliable than lsof)
- Add ps aux fallback for PID detection
- Implement structured bilingual VLM tags
- Add VLM integration documentation for Studio team

Endpoints tested and working with Momentry Studio AdminView UI.
This commit is contained in:
Accusys
2026-10-24 02:37:53 +08:00
parent d14cd9f3de
commit c151b49334
33 changed files with 3175 additions and 229 deletions
+321
View File
@@ -0,0 +1,321 @@
use axum::{
extract::State,
http::StatusCode,
Json,
};
use serde::{Deserialize, Serialize};
use std::process::Command;
use std::time::Duration;
use tokio::time::sleep;
use crate::api::types::AppState;
#[derive(Debug, Deserialize)]
pub struct ServiceStartRequest {
pub name: String,
#[serde(default)]
pub model: Option<String>,
#[serde(default = "default_port")]
pub port: u16,
}
fn default_port() -> u16 {
8080
}
#[derive(Debug, Deserialize)]
pub struct ServiceStopRequest {
pub name: String,
}
#[derive(Debug, Serialize)]
pub struct ServiceResponse {
pub result: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub pid: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct MbeHealthResponse {
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub uptime: Option<u64>,
}
/// Check if a port is in use by attempting to connect
fn is_port_in_use(port: u16) -> bool {
use std::net::TcpStream;
let addr = format!("127.0.0.1:{}", port);
match TcpStream::connect(&addr) {
Ok(_) => {
tracing::info!("[Service] Port {} is in use (connection successful)", port);
true
}
Err(e) => {
tracing::info!("[Service] Port {} not in use: {}", port, e);
false
}
}
}
/// Get PID of process listening on a port using lsof
fn get_port_pid(port: u16) -> Option<u32> {
// Try lsof first
let output = Command::new("/usr/sbin/lsof")
.args(["-nP", "-iTCP", &format!("{}", port), "-t"])
.output()
.ok()?;
if output.status.success() && !output.stdout.is_empty() {
let pid_str = String::from_utf8_lossy(&output.stdout);
return pid_str.trim().parse::<u32>().ok();
}
// Fallback: try to find by process name and port
let output = Command::new("ps")
.args(["aux"])
.output()
.ok()?;
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
if line.contains("llama-server") && line.contains(&format!("--port {}", port)) {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() > 1 {
return parts[1].parse::<u32>().ok();
}
}
}
None
}
/// Kill process by PID
fn kill_process(pid: u32) -> bool {
Command::new("kill")
.arg(pid.to_string())
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// Start llama.cpp server
async fn start_llama_server(port: u16, model: Option<String>) -> Result<u32, String> {
// Check if port is already in use
if is_port_in_use(port) {
if let Some(pid) = get_port_pid(port) {
tracing::info!("[Service] Port {} is occupied by PID {}, stopping it", port, pid);
kill_process(pid);
sleep(Duration::from_secs(2)).await;
}
}
// Default model path
let model_path = model.unwrap_or_else(|| {
"/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf".to_string()
});
let mmproj_path = "/Users/accusys/models/mmproj-F16.gguf";
let llama_binary = "/Users/accusys/llama.cpp/build/bin/llama-server";
tracing::info!("[Service] Spawning llama-server: {} with model {}", llama_binary, model_path);
// Start llama-server with proper PATH
let mut cmd = Command::new(llama_binary);
cmd.args([
"-m", &model_path,
"--mmproj", mmproj_path,
"--host", "0.0.0.0",
"--port", &port.to_string(),
"-ngl", "99",
"-c", "8192",
"--temp", "0.1",
"-b", "4096",
"-ub", "4096",
]);
// Set environment variables including PATH
cmd.env("PATH", "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin");
// Spawn the process
let mut child = cmd.spawn()
.map_err(|e| format!("Failed to start llama-server: {}", e))?;
let pid = child.id();
tracing::info!("[Service] Started llama-server with PID {}", pid);
// Detach the child process so it continues running independently
std::mem::forget(child);
// Wait for server to be ready
for i in 0..30 {
sleep(Duration::from_secs(2)).await;
if is_port_in_use(port) {
// Try to call health endpoint
let health_url = format!("http://127.0.0.1:{}/v1/models", port);
if let Ok(resp) = reqwest::get(&health_url).await {
if resp.status().is_success() {
tracing::info!("[Service] llama-server is ready after {} seconds", i * 2);
return Ok(pid);
}
}
}
}
Err("llama-server failed to start within 60 seconds".to_string())
}
/// Stop llama.cpp server
fn stop_llama_server(port: u16) -> Result<(), String> {
if let Some(pid) = get_port_pid(port) {
tracing::info!("[Service] Stopping llama-server on port {} (PID {})", port, pid);
if kill_process(pid) {
Ok(())
} else {
Err(format!("Failed to kill process {}", pid))
}
} else {
Err(format!("No service running on port {}", port))
}
}
/// Check MBE health
async fn check_mbe_health(port: u16) -> Result<MbeHealthResponse, String> {
tracing::info!("[Service] Checking MBE health on port {}", port);
if !is_port_in_use(port) {
tracing::warn!("[Service] Port {} not in use", port);
return Err("Port not in use".to_string());
}
tracing::info!("[Service] Port {} is in use, checking HTTP endpoint", port);
let url = format!("http://127.0.0.1:{}/v1/models", port);
let resp = reqwest::get(&url)
.await
.map_err(|e| format!("HTTP request failed: {}", e))?;
if !resp.status().is_success() {
return Err(format!("HTTP {}", resp.status()));
}
let json: serde_json::Value = resp.json().await
.map_err(|e| format!("Failed to parse JSON: {}", e))?;
tracing::info!("[Service] Health check response: {:?}", json);
// Extract model name from /v1/models response
let model = json["models"][0]["name"]
.as_str()
.map(|s| {
// Extract just the model name from path
s.split('/')
.last()
.unwrap_or(s)
.to_string()
});
Ok(MbeHealthResponse {
status: "ok".to_string(),
model,
uptime: Some(0), // Would need to track actual uptime
})
}
/// POST /api/v2/service/start
pub async fn start_service(
State(_state): State<AppState>,
Json(req): Json<ServiceStartRequest>,
) -> Result<Json<ServiceResponse>, StatusCode> {
tracing::info!("[Service] Start request received: {:?}", req);
if req.name != "mbe" {
tracing::error!("[Service] Invalid service name: {}", req.name);
return Err(StatusCode::BAD_REQUEST);
}
let port = req.port;
tracing::info!("[Service] Starting llama-server on port {}", port);
match start_llama_server(port, req.model).await {
Ok(pid) => {
tracing::info!("[Service] Successfully started llama-server with PID {}", pid);
Ok(Json(ServiceResponse {
result: "started".to_string(),
pid: Some(pid),
error: None,
}))
}
Err(e) => {
tracing::error!("[Service] Failed to start service: {}", e);
Ok(Json(ServiceResponse {
result: "failed".to_string(),
pid: None,
error: Some(e),
}))
}
}
}
/// POST /api/v2/service/stop
pub async fn stop_service(
State(_state): State<AppState>,
Json(req): Json<ServiceStopRequest>,
) -> Result<Json<ServiceResponse>, StatusCode> {
tracing::info!("[Service] Stop request: {:?}", req);
if req.name != "mbe" {
return Err(StatusCode::BAD_REQUEST);
}
let port = 8080;
match stop_llama_server(port) {
Ok(()) => {
Ok(Json(ServiceResponse {
result: "stopped".to_string(),
pid: None,
error: None,
}))
}
Err(e) => {
tracing::error!("[Service] Failed to stop service: {}", e);
Ok(Json(ServiceResponse {
result: "failed".to_string(),
pid: None,
error: Some(e),
}))
}
}
}
/// GET /api/v1/mbe/health
pub async fn mbe_health(
State(_state): State<AppState>,
) -> Result<Json<MbeHealthResponse>, StatusCode> {
let port = 8080;
match check_mbe_health(port).await {
Ok(health) => Ok(Json(health)),
Err(e) => {
tracing::error!("[Service] Health check failed: {}", e);
Ok(Json(MbeHealthResponse {
status: "offline".to_string(),
model: None,
uptime: None,
}))
}
}
}
pub fn router() -> axum::Router<AppState> {
axum::Router::new()
.route("/api/v2/service/start", axum::routing::post(start_service))
.route("/api/v2/service/stop", axum::routing::post(stop_service))
}