Files
leleka/crates/runtime-client/src/convert.rs
T

301 lines
11 KiB
Rust

//! Conversions between the backend contract and the `leleka.runtime.v1` wire messages, shared by
//! the server (`strata-desktop-core`) and the clients (the daemon gateway and `strata-next`).
use leleka_backend_api as api;
use std::net::SocketAddr;
use tonic::Status;
use crate::proto;
pub fn valid_token(token: &str) -> bool {
(32..=4096).contains(&token.len()) && token.bytes().all(|b| (0x21..=0x7e).contains(&b))
}
pub fn literal_loopback(address: SocketAddr) -> Result<(), Status> {
if !address.ip().is_loopback() {
return Err(Status::permission_denied("loopback_required"));
}
Ok(())
}
/// Only this marker is positive evidence of nonacceptance. Absence is uncertain.
pub fn refusal(code: tonic::Code, reason: &'static str) -> Status {
let mut status = Status::new(code, reason);
status.metadata_mut().insert(
"x-leleka-accepted",
"false".parse().expect("literal metadata"),
);
status
}
pub fn descriptor_to_proto(value: &api::ModelDescriptor) -> proto::ModelDescriptor {
proto::ModelDescriptor {
family: value.family.clone(),
architecture: value.architecture.clone(),
artifact_digest: value.artifact_digest.clone(),
weight_format: value.weight_format.clone(),
}
}
pub fn descriptor_from_proto(
value: &proto::ModelDescriptor,
) -> Result<api::ModelDescriptor, Status> {
let model = api::ModelDescriptor {
family: value.family.clone(),
architecture: value.architecture.clone(),
artifact_digest: value.artifact_digest.clone(),
weight_format: value.weight_format.clone(),
};
if [
model.family.len(),
model.architecture.len(),
model.weight_format.len(),
]
.into_iter()
.any(|n| n > 128)
|| model.validate().is_err()
{
return Err(refusal(
tonic::Code::InvalidArgument,
"invalid_model_descriptor",
));
}
Ok(model)
}
pub fn mode_to_proto(mode: &api::InferenceMode) -> proto::InferenceMode {
use proto::inference_mode::Selection;
let selection = match mode {
api::InferenceMode::Native => Selection::Native(proto::NativeMode {}),
api::InferenceMode::ExperimentalKarPle { profile_id } => {
Selection::KarPle(proto::KarPleMode {
profile_id: profile_id.clone(),
})
}
api::InferenceMode::ExperimentalMtp { profile_id } => Selection::Mtp(proto::MtpMode {
profile_id: profile_id.clone(),
}),
api::InferenceMode::ExperimentalKarExperts(e) => {
Selection::KarExperts(kar_experts_to_proto(e))
}
};
proto::InferenceMode {
selection: Some(selection),
}
}
fn kar_experts_to_proto(e: &api::KarExpertLoad) -> proto::KarExpertsMode {
proto::KarExpertsMode {
bundle_directory: e.bundle_directory.clone(),
archive_file: e.archive_file.clone(),
binding_file: e.binding_file.clone(),
provenance_file: e.provenance_file.clone(),
levels: u32::from(e.levels),
cache_mib: e.cache_mib,
prefill_mode: match e.prefill_mode {
api::KarPrefillMode::DecodeOnly => 1,
api::KarPrefillMode::AllRoutedBatched => 2,
},
}
}
pub fn config_to_proto(config: &api::RuntimeConfig) -> proto::LoadConfig {
proto::LoadConfig {
version: u32::from(config.load_config_version),
mode: Some(mode_to_proto(&config.inference_mode)),
gpu_memory_limit_bytes: config.gpu_memory_limit_bytes,
allow_experimental: config.allow_experimental,
}
}
pub fn config_from_proto(config: &proto::LoadConfig) -> Result<api::RuntimeConfig, Status> {
let mode = mode_from_proto(config.mode.as_ref().and_then(|m| m.selection.as_ref()))?;
let value = api::RuntimeConfig {
load_config_version: u16::try_from(config.version)
.map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_load_version"))?,
inference_mode: mode,
gpu_memory_limit_bytes: config.gpu_memory_limit_bytes,
allow_experimental: config.allow_experimental,
};
value
.validate()
.map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_load_config"))?;
Ok(value)
}
fn mode_from_proto(
selection: Option<&proto::inference_mode::Selection>,
) -> Result<api::InferenceMode, Status> {
use proto::inference_mode::Selection;
Ok(match selection {
Some(Selection::Native(_)) => api::InferenceMode::Native,
Some(Selection::KarPle(p)) => api::InferenceMode::ExperimentalKarPle {
profile_id: p.profile_id.clone(),
},
Some(Selection::Mtp(p)) => api::InferenceMode::ExperimentalMtp {
profile_id: p.profile_id.clone(),
},
Some(Selection::KarExperts(e)) => {
api::InferenceMode::ExperimentalKarExperts(kar_experts_from_proto(e)?)
}
None => {
return Err(refusal(
tonic::Code::InvalidArgument,
"missing_inference_mode",
));
}
})
}
fn kar_experts_from_proto(e: &proto::KarExpertsMode) -> Result<api::KarExpertLoad, Status> {
Ok(api::KarExpertLoad {
bundle_directory: e.bundle_directory.clone(),
archive_file: e.archive_file.clone(),
binding_file: e.binding_file.clone(),
provenance_file: e.provenance_file.clone(),
levels: u8::try_from(e.levels)
.map_err(|_| refusal(tonic::Code::InvalidArgument, "invalid_expert_levels"))?,
cache_mib: e.cache_mib,
prefill_mode: match e.prefill_mode {
1 => api::KarPrefillMode::DecodeOnly,
2 => api::KarPrefillMode::AllRoutedBatched,
_ => {
return Err(refusal(
tonic::Code::InvalidArgument,
"invalid_expert_prefill",
));
}
},
})
}
pub fn loaded_to_proto(value: &api::LoadedModel) -> proto::LoadedModel {
proto::LoadedModel {
handle: value.handle.clone(),
descriptor: Some(descriptor_to_proto(&value.descriptor)),
load_config_version: u32::from(value.load_config_version),
effective_mode: Some(mode_to_proto(&value.effective_mode)),
mode_identity_digest: value.mode_identity_digest.clone(),
}
}
/// The loaded model a runtime reports in a snapshot, as the backend contract describes it.
/// Experimental permission is implied by an experimental mode that is already running; this only
/// reads what the runtime says, it does not authorise a load.
pub fn loaded_from_proto(value: &proto::LoadedModel) -> Result<api::LoadedModel, Status> {
let descriptor = descriptor_from_proto(
value
.descriptor
.as_ref()
.ok_or_else(|| Status::data_loss("missing_loaded_descriptor"))?,
)?;
let config = config_from_proto(&proto::LoadConfig {
version: value.load_config_version,
mode: value.effective_mode.clone(),
gpu_memory_limit_bytes: None,
allow_experimental: true,
})?;
Ok(api::LoadedModel {
handle: value.handle.clone(),
descriptor,
load_config_version: config.load_config_version,
effective_mode: config.inference_mode,
mode_identity_digest: value.mode_identity_digest.clone(),
})
}
pub fn capabilities_from_proto(value: &proto::Capabilities) -> api::BackendCapabilities {
api::BackendCapabilities {
supported_models: value
.models
.iter()
.map(|m| api::SupportedModelTuple {
family: m.family.clone(),
architecture: m.architecture.clone(),
weight_format: m.weight_format.clone(),
})
.collect(),
max_concurrent_generations: value.max_concurrent_generations as usize,
supports_cancellation: value.cancellation,
supports_tool_call_streaming: value.tool_call_streaming,
}
}
fn usage_from_proto(value: &proto::Usage) -> api::Usage {
api::Usage {
input_tokens: value.input_tokens,
output_tokens: value.output_tokens,
reused_input_tokens: value.reused_input_tokens,
}
}
/// One generation frame as a backend event. A frame the contract cannot express is an error: the
/// caller must end the generation without a terminal event rather than invent one.
pub fn event_from_proto(
payload: proto::generation_frame::Payload,
) -> Result<api::GenerationEvent, Status> {
use proto::generation_frame::Payload;
Ok(match payload {
Payload::Accepted(_) => return Err(Status::data_loss("unexpected_accepted_frame")),
Payload::Text(text) => api::GenerationEvent::TextDelta { text: text.text },
Payload::Tool(tool) => api::GenerationEvent::ToolCallDelta {
index: tool.index,
id: tool.id,
name: tool.name,
arguments_delta: tool.arguments_delta,
},
Payload::Usage(usage) => api::GenerationEvent::Usage(usage_from_proto(&usage)),
Payload::Terminal(terminal) => {
api::GenerationEvent::Terminal(terminal_from_proto(terminal)?)
}
})
}
fn terminal_from_proto(terminal: proto::Terminal) -> Result<api::GenerationTerminal, Status> {
Ok(match terminal.state {
1 => completed_from_proto(&terminal)?,
2 => api::GenerationTerminal::Failed {
code: error_code_from_wire(terminal.error_code.as_str()),
message: terminal.reason,
retryable: terminal.retryable,
},
3 => api::GenerationTerminal::Cancelled,
_ => return Err(Status::data_loss("invalid_generation_terminal")),
})
}
fn completed_from_proto(terminal: &proto::Terminal) -> Result<api::GenerationTerminal, Status> {
Ok(api::GenerationTerminal::Completed {
reason: match terminal.reason.as_str() {
"stop" => api::FinishReason::Stop,
"length" => api::FinishReason::Length,
"tool_calls" => api::FinishReason::ToolCalls,
_ => return Err(Status::data_loss("unknown_finish_reason")),
},
usage: usage_from_proto(
terminal
.usage
.as_ref()
.ok_or_else(|| Status::data_loss("missing_terminal_usage"))?,
),
})
}
fn error_code_from_wire(code: &str) -> api::ErrorCode {
match code {
"invalid_request" => api::ErrorCode::InvalidRequest,
"unsupported_model" => api::ErrorCode::UnsupportedModel,
"resource_exhausted" => api::ErrorCode::ResourceExhausted,
"backend_unavailable" => api::ErrorCode::BackendUnavailable,
_ => api::ErrorCode::Internal,
}
}
/// The prompt and sampling controls of a backend request as wire fields.
pub fn apply_generation_request(
wire: &mut proto::GenerateRequest,
request: &api::GenerationRequest,
) {
wire.prompt = request.prompt.clone();
wire.max_output_tokens = request.max_output_tokens;
wire.temperature_milli = request.temperature_milli;
let s = &request.sampling;
wire.top_p_micro = s.top_p_micro;
wire.top_k = s.top_k;
wire.min_p_micro = s.min_p_micro;
wire.repetition_penalty_micro = s.repetition_penalty_micro;
wire.frequency_penalty_micro = s.frequency_penalty_micro;
wire.presence_penalty_micro = s.presence_penalty_micro;
wire.penalty_last_n = s.penalty_last_n;
wire.seed = s.seed;
}