Initial commit: MarkBaseEngine service
Features: - Wrapper service for llama-server with health monitoring - REST API for chat completions (/v1/chat/completions) - Admin endpoints (/admin/restart, /admin/status) - Auto-restart on crash with health check interval - Support for multimodal models (gemma-4-12b with mmproj) Configuration (config.json): - llama_server_path, model_path, mmproj_path - port: 8080, host: 0.0.0.0 - ctx_size: 8192, gpu_layers: 99 - batch_size: 4096, ubatch_size: 4096 (fixes GGML assertion error) - temperature: 0.1, max_tokens: 300 - auto_restart: true, health_check_interval: 30s Bug fixes: - Added batch_size and ubatch_size to prevent GGML assertion failure - Changed Axum server port to port+9 (8089) to avoid sftpgo conflict - Set gpu_layers to 99 instead of -1 for stable GPU offloading
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
Generated
+1915
File diff suppressed because it is too large
Load Diff
+18
@@ -0,0 +1,18 @@
|
|||||||
|
[package]
|
||||||
|
name = "markbaseengine"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum = "0.7"
|
||||||
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
reqwest = { version = "0.11", features = ["json"] }
|
||||||
|
anyhow = "1"
|
||||||
|
thiserror = "1"
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
tower = "0.4"
|
||||||
|
tower-http = { version = "0.5", features = ["cors", "trace"] }
|
||||||
|
clap = { version = "4", features = ["derive"] }
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# MarkBaseEngine v1
|
||||||
|
|
||||||
|
Rust-based LLM/VLM inference service manager for llama.cpp.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Model Management**: Start/stop/restart llama-server automatically
|
||||||
|
- **Health Monitoring**: Periodic health checks with auto-restart
|
||||||
|
- **OpenAI-compatible API**: Transparent proxy to llama.cpp
|
||||||
|
- **Configuration**: JSON-based model configuration
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo build --release
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./target/release/markbaseengine --config config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
- `GET /health` - Health check
|
||||||
|
- `GET /v1/models` - List models
|
||||||
|
- `POST /v1/chat/completions` - Chat completions
|
||||||
|
- `POST /admin/restart` - Restart LLM server
|
||||||
|
- `GET /admin/status` - Server status
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Edit `config.json` to specify:
|
||||||
|
- Model path
|
||||||
|
- Server port
|
||||||
|
- Context size
|
||||||
|
- GPU layers
|
||||||
|
- Temperature, max_tokens, etc.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"llama_server_path": "/Users/accusys/llama/bin/llama-server",
|
||||||
|
"model_path": "/Users/accusys/models/gemma-4-12b-it-Q4_K_M.gguf",
|
||||||
|
"mmproj_path": "/Users/accusys/models/mmproj-F16.gguf",
|
||||||
|
"port": 8080,
|
||||||
|
"host": "0.0.0.0",
|
||||||
|
"ctx_size": 8192,
|
||||||
|
"gpu_layers": 99,
|
||||||
|
"temperature": 0.1,
|
||||||
|
"max_tokens": 300,
|
||||||
|
"batch_size": 4096,
|
||||||
|
"ubatch_size": 4096,
|
||||||
|
"auto_restart": true,
|
||||||
|
"health_check_interval_secs": 30
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
use anyhow::Context;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ModelConfig {
|
||||||
|
pub llama_server_path: PathBuf,
|
||||||
|
pub model_path: PathBuf,
|
||||||
|
pub mmproj_path: Option<PathBuf>,
|
||||||
|
pub port: u16,
|
||||||
|
pub host: String,
|
||||||
|
pub ctx_size: usize,
|
||||||
|
pub gpu_layers: i32,
|
||||||
|
pub temperature: f32,
|
||||||
|
pub max_tokens: usize,
|
||||||
|
#[serde(default = "default_batch_size")]
|
||||||
|
pub batch_size: usize,
|
||||||
|
#[serde(default = "default_ubatch_size")]
|
||||||
|
pub ubatch_size: usize,
|
||||||
|
pub auto_restart: bool,
|
||||||
|
pub health_check_interval_secs: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_batch_size() -> usize { 4096 }
|
||||||
|
fn default_ubatch_size() -> usize { 4096 }
|
||||||
|
|
||||||
|
impl ModelConfig {
|
||||||
|
pub fn from_file(path: &PathBuf) -> anyhow::Result<Self> {
|
||||||
|
let content = std::fs::read_to_string(path)
|
||||||
|
.context("Failed to read config file")?;
|
||||||
|
let config: ModelConfig = serde_json::from_str(&content)
|
||||||
|
.context("Failed to parse config JSON")?;
|
||||||
|
|
||||||
|
config.validate()?;
|
||||||
|
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate(&self) -> anyhow::Result<()> {
|
||||||
|
if !self.llama_server_path.exists() {
|
||||||
|
anyhow::bail!("llama-server not found at {:?}", self.llama_server_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.model_path.exists() {
|
||||||
|
anyhow::bail!("Model not found at {:?}", self.model_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(mmproj) = &self.mmproj_path {
|
||||||
|
if !mmproj.exists() {
|
||||||
|
anyhow::bail!("mmproj not found at {:?}", mmproj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.port == 0 {
|
||||||
|
anyhow::bail!("Invalid port number");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum AppError {
|
||||||
|
#[error("Configuration error: {0}")]
|
||||||
|
Config(String),
|
||||||
|
|
||||||
|
#[error("Process management error: {0}")]
|
||||||
|
Process(String),
|
||||||
|
|
||||||
|
#[error("HTTP error: {0}")]
|
||||||
|
Http(#[from] reqwest::Error),
|
||||||
|
|
||||||
|
#[error("IO error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
|
||||||
|
#[error("JSON error: {0}")]
|
||||||
|
Json(#[from] serde_json::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl axum::response::IntoResponse for AppError {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
let (status, message) = match self {
|
||||||
|
AppError::Config(msg) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg),
|
||||||
|
AppError::Process(msg) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg),
|
||||||
|
AppError::Http(e) => (axum::http::StatusCode::BAD_GATEWAY, e.to_string()),
|
||||||
|
AppError::Io(e) => (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
|
||||||
|
AppError::Json(e) => (axum::http::StatusCode::BAD_REQUEST, e.to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
(status, axum::Json(serde_json::json!({ "error": message }))).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Result<T> = std::result::Result<T, AppError>;
|
||||||
+177
@@ -0,0 +1,177 @@
|
|||||||
|
mod config;
|
||||||
|
mod error;
|
||||||
|
mod manager;
|
||||||
|
|
||||||
|
use crate::config::ModelConfig;
|
||||||
|
use crate::error::{AppError, Result};
|
||||||
|
use crate::manager::ModelManager;
|
||||||
|
use axum::{
|
||||||
|
extract::State,
|
||||||
|
routing::{get, post},
|
||||||
|
Json, Router,
|
||||||
|
};
|
||||||
|
use clap::Parser;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
use tower_http::cors::{Any, CorsLayer};
|
||||||
|
use tracing::{info, Level};
|
||||||
|
use tracing_subscriber::FmtSubscriber;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
#[command(version, about, long_about = None)]
|
||||||
|
struct Args {
|
||||||
|
/// Path to config file
|
||||||
|
#[arg(short, long, default_value = "config.json")]
|
||||||
|
config: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct ChatRequest {
|
||||||
|
model: String,
|
||||||
|
messages: Vec<Message>,
|
||||||
|
#[serde(rename = "max_tokens")]
|
||||||
|
max_tokens: Option<usize>,
|
||||||
|
temperature: Option<f32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct Message {
|
||||||
|
role: String,
|
||||||
|
content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct ChatResponse {
|
||||||
|
id: String,
|
||||||
|
object: String,
|
||||||
|
created: u64,
|
||||||
|
model: String,
|
||||||
|
choices: Vec<Choice>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
struct Choice {
|
||||||
|
index: u32,
|
||||||
|
message: Message,
|
||||||
|
finish_reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AppState {
|
||||||
|
manager: Arc<Mutex<ModelManager>>,
|
||||||
|
config: ModelConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let args = Args::parse();
|
||||||
|
|
||||||
|
let subscriber = FmtSubscriber::builder()
|
||||||
|
.with_max_level(Level::INFO)
|
||||||
|
.finish();
|
||||||
|
tracing::subscriber::set_global_default(subscriber)?;
|
||||||
|
|
||||||
|
info!("Loading configuration from {:?}", args.config);
|
||||||
|
let config = ModelConfig::from_file(&args.config)?;
|
||||||
|
info!("Configuration loaded successfully");
|
||||||
|
|
||||||
|
let manager = ModelManager::new(config.clone());
|
||||||
|
let manager = Arc::new(Mutex::new(manager));
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut mgr = manager.lock().await;
|
||||||
|
mgr.start().await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let state = Arc::new(AppState {
|
||||||
|
manager: manager.clone(),
|
||||||
|
config: config.clone(),
|
||||||
|
});
|
||||||
|
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/health", get(health))
|
||||||
|
.route("/v1/models", get(list_models))
|
||||||
|
.route("/v1/chat/completions", post(chat_completions))
|
||||||
|
.route("/admin/restart", post(restart))
|
||||||
|
.route("/admin/status", get(status))
|
||||||
|
.layer(CorsLayer::new().allow_origin(Any).allow_methods(Any))
|
||||||
|
.with_state(state);
|
||||||
|
|
||||||
|
let addr = format!("{}:{}", config.host, config.port + 9);
|
||||||
|
info!("Starting MarkBaseEngine server on {}", addr);
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind(&addr).await?;
|
||||||
|
axum::serve(listener, app).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health() -> &'static str {
|
||||||
|
"OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn list_models(
|
||||||
|
State(state): State<Arc<AppState>>,
|
||||||
|
) -> Result<Json<serde_json::Value>> {
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"object": "list",
|
||||||
|
"data": [{
|
||||||
|
"id": state.config.model_path.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.unwrap_or("unknown"),
|
||||||
|
"object": "model",
|
||||||
|
"owned_by": "markbase",
|
||||||
|
"permission": [],
|
||||||
|
}]
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn chat_completions(
|
||||||
|
State(state): State<Arc<AppState>>,
|
||||||
|
Json(req): Json<ChatRequest>,
|
||||||
|
) -> Result<Json<ChatResponse>> {
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
let url = format!(
|
||||||
|
"http://localhost:{}/v1/chat/completions",
|
||||||
|
state.config.port
|
||||||
|
);
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.post(&url)
|
||||||
|
.json(&req)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| AppError::Http(e))?;
|
||||||
|
|
||||||
|
let chat_response: ChatResponse = response
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| AppError::Http(e))?;
|
||||||
|
|
||||||
|
Ok(Json(chat_response))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn restart(State(state): State<Arc<AppState>>) -> Result<Json<serde_json::Value>> {
|
||||||
|
let mut manager = state.manager.lock().await;
|
||||||
|
manager.restart().await?;
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"status": "restarted",
|
||||||
|
"message": "LLM server restarted successfully"
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn status(State(state): State<Arc<AppState>>) -> Result<Json<serde_json::Value>> {
|
||||||
|
let mut manager = state.manager.lock().await;
|
||||||
|
let is_running = manager.is_running();
|
||||||
|
let health = manager.health_check().await;
|
||||||
|
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"llm_server": {
|
||||||
|
"running": is_running,
|
||||||
|
"healthy": health,
|
||||||
|
"port": manager.get_port(),
|
||||||
|
}
|
||||||
|
})))
|
||||||
|
}
|
||||||
+129
@@ -0,0 +1,129 @@
|
|||||||
|
use crate::config::ModelConfig;
|
||||||
|
use crate::error::{AppError, Result};
|
||||||
|
use std::process::Child;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::time::sleep;
|
||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
|
pub struct ModelManager {
|
||||||
|
config: ModelConfig,
|
||||||
|
process: Option<Child>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModelManager {
|
||||||
|
pub fn new(config: ModelConfig) -> Self {
|
||||||
|
Self {
|
||||||
|
config,
|
||||||
|
process: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start(&mut self) -> Result<()> {
|
||||||
|
info!("Starting llama-server on port {}", self.config.port);
|
||||||
|
|
||||||
|
let mut cmd = std::process::Command::new(&self.config.llama_server_path);
|
||||||
|
cmd.arg("-m")
|
||||||
|
.arg(&self.config.model_path)
|
||||||
|
.arg("--port")
|
||||||
|
.arg(self.config.port.to_string())
|
||||||
|
.arg("--host")
|
||||||
|
.arg(&self.config.host)
|
||||||
|
.arg("--ctx-size")
|
||||||
|
.arg(self.config.ctx_size.to_string())
|
||||||
|
.arg("-ngl")
|
||||||
|
.arg(self.config.gpu_layers.to_string())
|
||||||
|
.arg("-b")
|
||||||
|
.arg(self.config.batch_size.to_string())
|
||||||
|
.arg("-ub")
|
||||||
|
.arg(self.config.ubatch_size.to_string());
|
||||||
|
|
||||||
|
if let Some(mmproj) = &self.config.mmproj_path {
|
||||||
|
info!("Loading mmproj from {:?}", mmproj);
|
||||||
|
cmd.arg("--mmproj").arg(mmproj);
|
||||||
|
}
|
||||||
|
|
||||||
|
let process = cmd
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| AppError::Process(format!("Failed to start llama-server: {}", e)))?;
|
||||||
|
|
||||||
|
self.process = Some(process);
|
||||||
|
|
||||||
|
info!("Waiting for llama-server to be ready...");
|
||||||
|
self.wait_for_ready().await?;
|
||||||
|
|
||||||
|
info!("llama-server started successfully");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn stop(&mut self) -> Result<()> {
|
||||||
|
if let Some(mut process) = self.process.take() {
|
||||||
|
info!("Stopping llama-server");
|
||||||
|
process
|
||||||
|
.kill()
|
||||||
|
.map_err(|e| AppError::Process(format!("Failed to kill llama-server: {}", e)))?;
|
||||||
|
process
|
||||||
|
.wait()
|
||||||
|
.map_err(|e| AppError::Process(format!("Failed to wait for process: {}", e)))?;
|
||||||
|
info!("llama-server stopped");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn restart(&mut self) -> Result<()> {
|
||||||
|
info!("Restarting llama-server");
|
||||||
|
self.stop().await?;
|
||||||
|
sleep(Duration::from_secs(2)).await;
|
||||||
|
self.start().await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn health_check(&self) -> bool {
|
||||||
|
let url = format!("http://localhost:{}/health", self.config.port);
|
||||||
|
match reqwest::get(&url).await {
|
||||||
|
Ok(resp) => resp.status().is_success(),
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Health check failed: {}", e);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait_for_ready(&self) -> Result<()> {
|
||||||
|
let max_retries = 30;
|
||||||
|
let retry_delay = Duration::from_secs(1);
|
||||||
|
|
||||||
|
for i in 0..max_retries {
|
||||||
|
if self.health_check().await {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
if i < max_retries - 1 {
|
||||||
|
sleep(retry_delay).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(AppError::Process(
|
||||||
|
"llama-server failed to become ready within timeout".to_string(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_running(&mut self) -> bool {
|
||||||
|
if let Some(process) = &mut self.process {
|
||||||
|
matches!(process.try_wait(), Ok(None))
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_port(&self) -> u16 {
|
||||||
|
self.config.port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ModelManager {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(mut process) = self.process.take() {
|
||||||
|
let _ = process.kill();
|
||||||
|
let _ = process.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user