//! Sampling controls on the runtime gRPC contract: JSON request fields <-> fixed point <-> //! `runtime.proto` `GenerateRequest` <-> `backend-api` `SamplingOptions`. The arithmetic and the //! Original's ranges live in `leleka-serving-policy` (tested on every host); this file is the thin //! field-by-field mapping. use leleka_backend_api::SamplingOptions; use leleka_sampler_ref::params::FixedPoint; use leleka_serving_policy::fixed::{error_code, sampling_from_object, to_fixed_point}; use serde_json::{Map, Value}; use crate::runtime_rpc::proto; /// Read and validate the sampling fields of a Responses request object. pub(crate) fn from_json(object: &Map) -> Result { let sampling = sampling_from_object(object).map_err(|e| error_code(&e))?; to_fixed_point(&sampling).map_err(|e| error_code(&e)) } /// Put the sampling controls on a runtime request. pub(crate) fn apply(request: &mut proto::GenerateRequest, fixed: &FixedPoint) { request.temperature_milli = fixed.temperature_milli; request.top_p_micro = fixed.top_p_micro; request.top_k = fixed.top_k; request.min_p_micro = fixed.min_p_micro; request.repetition_penalty_micro = fixed.repetition_penalty_micro; request.frequency_penalty_micro = fixed.frequency_penalty_micro; request.presence_penalty_micro = fixed.presence_penalty_micro; request.penalty_last_n = fixed.penalty_last_n; request.seed = fixed.seed; } /// Validate a received request's controls at the RPC boundary (the backend validates again) and /// convert them for the backend. pub(crate) fn to_backend(command: &proto::GenerateRequest) -> Result { let fixed = FixedPoint { temperature_milli: command.temperature_milli, top_p_micro: command.top_p_micro, top_k: command.top_k, min_p_micro: command.min_p_micro, repetition_penalty_micro: command.repetition_penalty_micro, frequency_penalty_micro: command.frequency_penalty_micro, presence_penalty_micro: command.presence_penalty_micro, penalty_last_n: command.penalty_last_n, seed: command.seed, }; // The same contract as the HTTP boundary: the ranges of `RequestSampling::validate`. leleka_sampler_ref::RequestSampling::from_fixed_point(&fixed) .validate() .map_err(|_| ())?; Ok(SamplingOptions { top_p_micro: fixed.top_p_micro, top_k: fixed.top_k, min_p_micro: fixed.min_p_micro, repetition_penalty_micro: fixed.repetition_penalty_micro, frequency_penalty_micro: fixed.frequency_penalty_micro, presence_penalty_micro: fixed.presence_penalty_micro, penalty_last_n: fixed.penalty_last_n, seed: fixed.seed, }) }