Files
strata-ctl/examples/serve_mock.rs
T
adm 597ac432e1 strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API)
From-scratch rewrite of the Python serve (Python kept as behavioral spec).

- engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog,
  abort, is_idle probe.
- config: tolerant shared-JSON loader; foreign keys ignored so one file drives
  strata-ctl and uostream; CLI --config/--host/--port/--serve.
- inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template
  via minijinja; channel-token dialect (reasoning streamed live); image bridge
  (in-process Vision, image=<path>); formatter assembling the API seam.
- api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health;
  reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side
  execution); stop sequences with hold-back; abort on client disconnect.

69 tests green + 2 real-file ignored; clippy clean. Text, images and tools
validated live against the real Inkling engine.
2026-11-24 05:28:56 +01:00

94 lines
3.0 KiB
Rust

//! Live smoke demo of the OpenAI surface over a real TCP socket, driven by the
//! scripted mock engine (tests/mock_engine.py) and a byte-level formatter — so
//! you can `curl` it without a GPU or the Inkling tokenizer.
//!
//! cargo run --example serve_mock # listens on 127.0.0.1:8080
//!
//! curl -s localhost:8080/v1/models
//! curl -s localhost:8080/v1/chat/completions -H 'content-type: application/json' \
//! -d '{"model":"mock","messages":[{"role":"user","content":"hi"}]}'
//! # streaming (watch the SSE flush token by token):
//! curl -N localhost:8080/v1/chat/completions -H 'content-type: application/json' \
//! -d '{"model":"mock","messages":[{"role":"user","content":"hi"}],"stream":true}'
use std::sync::Arc;
use std::time::Duration;
use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt};
use strata_ctl::api::service::ChatService;
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
use strata_ctl::engine::Engine;
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
struct ByteFormatter;
impl Formatter for ByteFormatter {
fn model_name(&self) -> &str {
"mock"
}
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
let text = req
.messages
.iter()
.rev()
.find_map(|m| m.text())
.unwrap_or("")
.to_string();
Ok(Prompt {
ids: text.bytes().map(u32::from).collect(),
max_new: req.max_new(64),
sampling: Default::default(),
temp_files: Vec::new(),
})
}
fn decoder(&self) -> Box<dyn Decoder> {
Box::new(ByteDecoder)
}
}
struct ByteDecoder;
impl Decoder for ByteDecoder {
fn push(&mut self, id: u32) -> Vec<Piece> {
if id < 256 {
vec![Piece::Content(char::from(id as u8).to_string())]
} else {
Vec::new()
}
}
fn finish(&mut self, _reason: Option<&str>) -> Vec<Piece> {
Vec::new()
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let engine = Arc::new(
Engine::start(
"python3",
&[MOCK.to_string()],
None,
Duration::from_secs(15),
)
.await
.expect("failed to start the mock engine (is python3 available?)"),
);
println!(
"mock engine READY, context {} tokens",
engine.ready().max_context
);
let svc = ChatService::new(engine.clone(), Arc::new(ByteFormatter));
let app = strata_ctl::api::router(svc);
let addr = std::env::var("ADDR").unwrap_or_else(|_| "127.0.0.1:8080".into());
let listener = tokio::net::TcpListener::bind(&addr).await?;
println!("listening on http://{addr} (Ctrl-C to stop)");
axum::serve(listener, app)
.with_graceful_shutdown(async move {
let _ = tokio::signal::ctrl_c().await;
println!("\nshutting down");
let _ = engine.shutdown().await;
})
.await?;
Ok(())
}