A high-performance inference engine for AI models
Decision model CLI support (#1039)
Aleksandr Golokoza1713f31ebf8
diff --git a/crates/legacy/cli/src/interactive/components/application.rs b/crates/legacy/cli/src/interactive/components/application.rsindex 8906f3422..37c4e5e04 100644--- a/crates/legacy/cli/src/interactive/components/application.rs+++ b/crates/legacy/cli/src/interactive/components/application.rs@@ -3,7 +3,7 @@ use std::path::PathBuf;use iocraft::prelude::*;use shoji::types::{basic::{ReasoningEffort, SamplingParameters},- model::Model,+ model::{Model, ModelSpecialization},};use uzu::{engine::Engine,@@ -253,6 +253,15 @@ pub fn Application(return;};sessions::classification::run_session(state, session, text).await;+ } else if model.specializations.contains(&ModelSpecialization::Decision {}) {+ let has_running_session = state.read().session_state().is_some_and(SessionState::is_busy);+ if has_running_session {+ return;+ }+ let Some(session) = sessions::decision::ensure_session(state, &model).await else {+ return;+ };+ sessions::decision::run_session(state, session, text).await;} else if model.is_text_to_speech_capable() {let has_running_session = state.read().session_state().is_some_and(SessionState::is_busy);if has_running_session {@@ -317,6 +326,10 @@ pub fn Application(return;}+ if is_escape && sessions::decision::leave_question_mode(&mut state) {+ return;+ }+state.flow = Some(Box::new(ExitFlow));});diff --git a/crates/legacy/cli/src/interactive/components/command_input.rs b/crates/legacy/cli/src/interactive/components/command_input.rsindex 40cbc672d..fff9f935a 100644--- a/crates/legacy/cli/src/interactive/components/command_input.rs+++ b/crates/legacy/cli/src/interactive/components/command_input.rs@@ -1,11 +1,17 @@use iocraft::prelude::*;+use shoji::types::model::ModelSpecialization;use unicode_width::UnicodeWidthStr;use uzu::storage::DownloadPhase;use crate::interactive::{components::{ApplicationState, InputType, Selector, SelectorItem, SelectorStyle, TextInput, TextInputFocus},flows::Command,- helpers::{HINT_COMMANDS, HINT_SEND, HINT_STORAGE_DELETE, HINT_STORAGE_PAUSE_RESUME, SYMBOL_COMMAND, SYMBOL_INPUT},+ helpers::{+ HINT_COMMANDS, HINT_DECISION_QUESTION_EXAMPLES, HINT_DECISION_QUESTION_NOTES, HINT_DECISION_QUESTION_TITLE,+ HINT_DECISION_STATE_EXAMPLES, HINT_DECISION_STATE_NOTES, HINT_DECISION_STATE_TITLE, HINT_SEND,+ HINT_STORAGE_DELETE, HINT_STORAGE_PAUSE_RESUME, HintExample, SYMBOL_COMMAND, SYMBOL_INPUT,+ },+ sessions::decision::is_question_mode,};const SAFE_PADDING: u16 = 1;@@ -113,13 +119,35 @@ fn hint_component(},}hints.push(HINT_COMMANDS.to_string());+ let is_decision_model = state+ .read()+ .model_state+ .as_ref()+ .is_some_and(|model_state| model_state.model.specializations.contains(&ModelSpecialization::Decision {}));if commands.is_empty() {return element! {- Text(- content: hints.join("\n"),- color: state.read().theme().subtitle_color,- )+ View(flex_direction: FlexDirection::Column) {+ Text(+ content: hints.join("\n"),+ color: state.read().theme().subtitle_color,+ )+ #(is_decision_model.then(|| if is_question_mode(&state.read()) {+ decision_guide_component(+ state,+ HINT_DECISION_QUESTION_TITLE,+ HINT_DECISION_QUESTION_EXAMPLES,+ HINT_DECISION_QUESTION_NOTES,+ )+ } else {+ decision_guide_component(+ state,+ HINT_DECISION_STATE_TITLE,+ HINT_DECISION_STATE_EXAMPLES,+ HINT_DECISION_STATE_NOTES,+ )+ }))+ }}.into();}@@ -154,3 +182,53 @@ fn hint_component(}.into()}++fn decision_guide_component(+ state: State<ApplicationState>,+ title: &'static str,+ examples: &'static [HintExample],+ notes: &'static [&'static str],+) -> AnyElement<'static> {+ let theme = state.read().theme().clone();+ let label_width = examples.iter().map(|example| UnicodeWidthStr::width(example.label) as u16).max().unwrap_or(0);+ let lines_width = examples+ .iter()+ .flat_map(|example| example.lines.iter())+ .map(|line| UnicodeWidthStr::width(*line) as u16)+ .max()+ .unwrap_or(0);+ let rows: Vec<AnyElement<'static>> = examples+ .iter()+ .map(|example| {+ element! {+ View(flex_direction: FlexDirection::Row, column_gap: theme.padding_wide()) {+ View(width: label_width) {+ Text(content: example.label, color: theme.subtitle_color)+ }+ View(width: lines_width) {+ Text(content: example.lines.join("\n"))+ }+ Text(content: example.note, color: theme.subtitle_color)+ }+ }+ .into()+ })+ .collect();++ element! {+ View(+ width: 100pct,+ flex_direction: FlexDirection::Column,+ row_gap: theme.padding(),+ border_style: BorderStyle::Single,+ border_color: theme.subtitle_color,+ padding_left: theme.padding(),+ padding_right: theme.padding(),+ ) {+ Text(content: title, weight: Weight::Bold)+ #(rows.into_iter())+ Text(content: notes.join("\n"), color: theme.subtitle_color)+ }+ }+ .into()+}diff --git a/crates/legacy/cli/src/interactive/components/history_cell.rs b/crates/legacy/cli/src/interactive/components/history_cell.rsindex f3721a2c8..77c89a90b 100644--- a/crates/legacy/cli/src/interactive/components/history_cell.rs+++ b/crates/legacy/cli/src/interactive/components/history_cell.rs@@ -1,13 +1,21 @@use iocraft::prelude::*;use shoji::types::session::{- chat::ChatReplyStats, classification::ClassificationOutput, text_to_speech::TextToSpeechStats,+ chat::ChatReplyStats,+ classification::ClassificationOutput,+ decision::{DecisionAnswer, DecisionQuestion, DecisionResult},+ text_to_speech::TextToSpeechStats,};+use unicode_width::UnicodeWidthStr;use crate::interactive::{- components::ApplicationState,+ components::{ApplicationState, ProgressBar},helpers::{SYMBOL_COMMAND, SYMBOL_INPUT, SYMBOL_INPUT_RESULT, SYMBOL_LONG_DASH},+ sessions::decision::question_title,};+const DECISION_CHOICE_LIMIT: usize = 5;+const DECISION_BAR_WIDTH: u16 = 24;+#[derive(Clone)]pub enum TranscriptItem {Thinking(String),@@ -36,6 +44,10 @@ pub enum HistoryCellType {ClassificationOutput {output: ClassificationOutput,},+ DecisionOutput {+ question: DecisionQuestion,+ result: DecisionResult,+ },TextToSpeechOutput {stats: TextToSpeechStats,},@@ -108,6 +120,10 @@ pub fn HistoryCell(Some(HistoryCellType::ClassificationOutput {output,}) => classification_output_component(output, theme.subtitle_color, theme.padding()),+ Some(HistoryCellType::DecisionOutput {+ question,+ result,+ }) => decision_output_component(question, result, theme.accent_color, theme.subtitle_color, theme.padding()),Some(HistoryCellType::TextToSpeechOutput {stats,}) => text_to_speech_output_component(stats, theme.subtitle_color, theme.padding()),@@ -288,6 +304,174 @@ fn classification_output_component(.into()}+fn decision_output_component(+ question: DecisionQuestion,+ result: DecisionResult,+ accent_color: Color,+ subtitle_color: Color,+ padding: u16,+) -> AnyElement<'static> {+ let tokens_count = result.stats.tokens_count;+ let duration = result.stats.total_duration;++ element! {+ View(+ width: 100pct,+ border_style: BorderStyle::Single,+ border_color: subtitle_color,+ flex_direction: FlexDirection::Column,+ row_gap: padding,+ padding_left: padding,+ padding_right: padding,+ ) {+ #(decision_answer_component(question, result.answer, accent_color, subtitle_color, padding))+ Text(+ content: format!("{tokens_count} tokens · {duration:.2} s"),+ color: subtitle_color,+ )+ }+ }+ .into()+}++struct DecisionRow {+ label: String,+ probability: f64,+ selected: bool,+}++// Choice options are listed from most to least probable, score levels in scale order and a yes/no answer as its verdict.+fn decision_answer_component(+ question: DecisionQuestion,+ answer: DecisionAnswer,+ accent_color: Color,+ subtitle_color: Color,+ padding: u16,+) -> AnyElement<'static> {+ let title = question_title(&question);+ let (rows, hidden_count, score) = match (question, answer) {+ (+ DecisionQuestion::Choice {+ options,+ ..+ },+ DecisionAnswer::Choice {+ index,+ probabilities,+ ..+ },+ ) => {+ let mut order = (0..options.len().min(probabilities.len())).collect::<Vec<_>>();+ // Stable, so tied options keep their order and the chosen one comes first, as `decide` picks it.+ order.sort_by(|first, second| probabilities[*second].total_cmp(&probabilities[*first]));+ let hidden_count = order.len().saturating_sub(DECISION_CHOICE_LIMIT);+ let rows = order+ .into_iter()+ .take(DECISION_CHOICE_LIMIT)+ .map(|option_index| DecisionRow {+ label: options[option_index].key.clone(),+ probability: probabilities[option_index],+ selected: option_index as i64 == index,+ })+ .collect();+ (rows, hidden_count, None)+ },+ (+ DecisionQuestion::Score {+ levels,+ ..+ },+ DecisionAnswer::Score {+ probabilities,+ score,+ },+ ) => {+ let likeliest = (1..probabilities.len()).fold(0, |best, index| {+ if probabilities[index] > probabilities[best] {+ index+ } else {+ best+ }+ });+ let rows = levels+ .into_iter()+ .zip(probabilities)+ .enumerate()+ .map(|(index, (label, probability))| DecisionRow {+ label,+ probability,+ selected: index == likeliest,+ })+ .collect();+ (rows, 0, Some(score))+ },+ (+ DecisionQuestion::YesNo {+ ..+ },+ DecisionAnswer::YesNo {+ yes_probability,+ },+ ) => {+ let (label, probability) = if yes_probability >= 0.5 {+ ("yes", yes_probability)+ } else {+ ("no", 1.0 - yes_probability)+ };+ let row = DecisionRow {+ label: label.to_string(),+ probability,+ selected: true,+ };+ (vec![row], 0, None)+ },+ _ => (Vec::new(), 0, None),+ };++ let label_width = rows.iter().map(|row| UnicodeWidthStr::width(row.label.as_str()) as u16).max().unwrap_or(0);+ let rows: Vec<AnyElement<'static>> = rows+ .into_iter()+ .map(|row| {+ let label_color = row.selected.then_some(accent_color);+ let weight = if row.selected {+ Weight::Bold+ } else {+ Weight::Normal+ };+ element! {+ View(flex_direction: FlexDirection::Row, column_gap: padding) {+ View(width: label_width) {+ Text(content: row.label, color: label_color, weight: weight)+ }+ View(width: DECISION_BAR_WIDTH) {+ ProgressBar(progress: row.probability as f32)+ }+ Text(content: format!("{:.4}", row.probability), color: label_color, weight: weight)+ }+ }+ .into()+ })+ .collect();++ element! {+ View(width: 100pct, flex_direction: FlexDirection::Column) {+ View(flex_direction: FlexDirection::Row, column_gap: padding) {+ Text(content: title, weight: Weight::Bold)+ #(score.map(|score| element! {+ Text(content: format!("{score:.2}"), color: accent_color, weight: Weight::Bold)+ }))+ }+ View(flex_direction: FlexDirection::Column, padding_left: padding) {+ #(rows.into_iter())+ #((hidden_count > 0).then(|| element! {+ Text(content: format!("+{hidden_count} more"), color: subtitle_color)+ }))+ }+ }+ }+ .into()+}+fn chat_reply_stats_component(stats: &ChatReplyStats,subtitle_color: Color,diff --git a/crates/legacy/cli/src/interactive/components/rendered_text.rs b/crates/legacy/cli/src/interactive/components/rendered_text.rsindex 7b3f69a81..782706bd2 100644--- a/crates/legacy/cli/src/interactive/components/rendered_text.rs+++ b/crates/legacy/cli/src/interactive/components/rendered_text.rs@@ -112,6 +112,10 @@ impl RenderedText {self.position += next_length.saturating_sub(previous_length);}+ pub fn previous_grapheme(&self) -> Option<&str> {+ self.position.checked_sub(1).and_then(|index| self.original_text.graphemes(true).nth(index))+ }+pub fn remove_character(&mut self) {if self.position == 0 {return;diff --git a/crates/legacy/cli/src/interactive/components/text_input.rs b/crates/legacy/cli/src/interactive/components/text_input.rsindex 45924e1e4..1e32cbfe7 100644--- a/crates/legacy/cli/src/interactive/components/text_input.rs+++ b/crates/legacy/cli/src/interactive/components/text_input.rs@@ -6,7 +6,7 @@ use std::{use iocraft::prelude::*;use tokio::sync::watch;-use crate::interactive::components::RenderedText;+use crate::interactive::{components::RenderedText, helpers::SYMBOL_LINE_CONTINUATION};const ENTER_SUBMIT_DELAY: Duration = Duration::from_millis(50);@@ -90,6 +90,18 @@ pub fn TextInput(let Some(mut state) = state.try_write() else {continue;};+ // Most terminals send Shift+Enter as a plain Enter, so a typed Enter right after `\` starts a new line.+ // Pasted text never gets here: the next pasted key arrives before the delay ends.+ if state.previous_grapheme() == Some(SYMBOL_LINE_CONTINUATION) {+ state.remove_character();+ state.add_character('\n');+ let text = state.original_text.clone();+ drop(state);+ if let Ok(mut handlers) = handlers.lock() {+ (handlers.on_change)(text);+ }+ continue;+ }let text = state.original_text.clone();state.reset();drop(state);@@ -191,6 +203,14 @@ pub fn TextInput(state.write().add_character('\n');notify_change();},+ // Ctrl+J is a line feed, which every terminal sends as is.+ KeyCode::Char('j') if modifiers.contains(KeyModifiers::CONTROL) => {+ if focus.is_minimal() {+ return;+ }+ state.write().add_character('\n');+ notify_change();+ },KeyCode::Enter => {if focus.is_minimal() {return;diff --git a/crates/legacy/cli/src/interactive/helpers/hint.rs b/crates/legacy/cli/src/interactive/helpers/hint.rsindex e3db8cd35..61f063eba 100644--- a/crates/legacy/cli/src/interactive/helpers/hint.rs+++ b/crates/legacy/cli/src/interactive/helpers/hint.rs@@ -1,5 +1,40 @@pub const HINT_COMMANDS: &str = "/ for commands";pub const HINT_SEND: &str = "enter to send";+// An example input, line by line, with what it is and a note on how it's written.+pub struct HintExample {+ pub label: &'static str,+ pub lines: &'static [&'static str],+ pub note: &'static str,+}++pub const HINT_DECISION_STATE_TITLE: &str = "Write the text you want to ask questions about, then press enter";+pub const HINT_DECISION_STATE_EXAMPLES: &[HintExample] = &[HintExample {+ label: "for example",+ lines: &["This LLM runs right on my laptop and answers in under a second, love it!"],+ note: "a message, a document or JSON",+}];+pub const HINT_DECISION_STATE_NOTES: &[&str] = &["ctrl+j, or \\ then enter, starts a new line"];+pub const HINT_DECISION_QUESTION_TITLE: &str =+ "Ask a question about the text, then press enter. Each question is sent on its own";+pub const HINT_DECISION_QUESTION_EXAMPLES: &[HintExample] = &[+ HintExample {+ label: "yes or no",+ lines: &["Does the user like the model?"],+ note: "just the question",+ },+ HintExample {+ label: "choice",+ lines: &["What does the user praise?", "speed: how fast it answers", "accuracy", "price"],+ note: "one option per line, a description after : is optional",+ },+ HintExample {+ label: "score",+ lines: &["How enthusiastic is the user?", "Low < Medium < High"],+ note: "levels on one line, from lowest to highest",+ },+];+pub const HINT_DECISION_QUESTION_NOTES: &[&str] =+ &["esc to change the text", "ctrl+j, or \\ then enter, starts a new line"];pub const HINT_STORAGE_PAUSE_RESUME: &str = "ctrl+p to pause/resume download";pub const HINT_STORAGE_DELETE: &str = "ctrl+d to delete model";pub const HINT_SESSION_INTERRUPT: &str = "esc to interrupt";diff --git a/crates/legacy/cli/src/interactive/helpers/mod.rs b/crates/legacy/cli/src/interactive/helpers/mod.rsindex aee170d48..e4e0db5c6 100644--- a/crates/legacy/cli/src/interactive/helpers/mod.rs+++ b/crates/legacy/cli/src/interactive/helpers/mod.rs@@ -3,5 +3,12 @@ mod hint;mod symbol;pub use color::ColorRgb;-pub use hint::{HINT_COMMANDS, HINT_SEND, HINT_SESSION_INTERRUPT, HINT_STORAGE_DELETE, HINT_STORAGE_PAUSE_RESUME};-pub use symbol::{SYMBOL_COMMAND, SYMBOL_CURSOR, SYMBOL_INPUT, SYMBOL_INPUT_RESULT, SYMBOL_LONG_DASH, SYMBOL_NEW_LINE};+pub use hint::{+ HINT_COMMANDS, HINT_DECISION_QUESTION_EXAMPLES, HINT_DECISION_QUESTION_NOTES, HINT_DECISION_QUESTION_TITLE,+ HINT_DECISION_STATE_EXAMPLES, HINT_DECISION_STATE_NOTES, HINT_DECISION_STATE_TITLE, HINT_SEND,+ HINT_SESSION_INTERRUPT, HINT_STORAGE_DELETE, HINT_STORAGE_PAUSE_RESUME, HintExample,+};+pub use symbol::{+ SYMBOL_COMMAND, SYMBOL_CURSOR, SYMBOL_INPUT, SYMBOL_INPUT_RESULT, SYMBOL_LINE_CONTINUATION, SYMBOL_LONG_DASH,+ SYMBOL_NEW_LINE,+};diff --git a/crates/legacy/cli/src/interactive/helpers/symbol.rs b/crates/legacy/cli/src/interactive/helpers/symbol.rsindex 2f132a76b..12269d458 100644--- a/crates/legacy/cli/src/interactive/helpers/symbol.rs+++ b/crates/legacy/cli/src/interactive/helpers/symbol.rs@@ -4,3 +4,4 @@ pub const SYMBOL_CURSOR: &str = "█";pub const SYMBOL_NEW_LINE: &str = "\n";pub const SYMBOL_COMMAND: &str = "/";pub const SYMBOL_LONG_DASH: &str = "—";+pub const SYMBOL_LINE_CONTINUATION: &str = "\\";diff --git a/crates/legacy/cli/src/interactive/sessions/decision.rs b/crates/legacy/cli/src/interactive/sessions/decision.rsnew file mode 100644index 000000000..437346be9--- /dev/null+++ b/crates/legacy/cli/src/interactive/sessions/decision.rs@@ -0,0 +1,271 @@+use std::any::Any;++use iocraft::prelude::*;+use nagare::decision::{DecisionSession, DecisionSessionError};+use shoji::types::{+ model::Model,+ session::decision::{DecisionInput, DecisionOption, DecisionQuestion},+};++use crate::interactive::{+ components::{ApplicationState, HistoryCellType},+ sessions::SessionState,+};++const SCORE_LEVELS_SEPARATOR: char = '<';+const OPTION_DESCRIPTION_SEPARATOR: char = ':';++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum DecisionSessionStatus {+ Idle,+ Loading,+ Deciding,+}++// Without a current state the session waits for one (state mode); with it, every input is a question about it+// (question mode).+#[derive(Clone)]+pub struct DecisionSessionState {+ session: Option<DecisionSession>,+ status: DecisionSessionStatus,+ current_state: Option<String>,+}++impl DecisionSessionState {+ pub fn loading() -> Self {+ Self {+ session: None,+ status: DecisionSessionStatus::Loading,+ current_state: None,+ }+ }++ pub fn idle(session: DecisionSession) -> Self {+ Self {+ session: Some(session),+ status: DecisionSessionStatus::Idle,+ current_state: None,+ }+ }+}++impl SessionState for DecisionSessionState {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn as_any_mut(&mut self) -> &mut dyn Any {+ self+ }++ fn is_busy(&self) -> bool {+ matches!(self.status, DecisionSessionStatus::Loading | DecisionSessionStatus::Deciding)+ }++ fn interrupt(&self) -> bool {+ false+ }++ fn status_text(&self) -> Option<String> {+ let status = match self.status {+ DecisionSessionStatus::Idle => "loaded".to_string(),+ DecisionSessionStatus::Loading => "loading".to_string(),+ DecisionSessionStatus::Deciding => "deciding".to_string(),+ };+ Some(status)+ }++ fn pending_history_cell(&self) -> Option<HistoryCellType> {+ None+ }+}++pub async fn ensure_session(+ state: State<ApplicationState>,+ model: &Model,+) -> Option<DecisionSession> {+ let mut state = state;+ {+ let state = state.read();+ if let Some(session) = decision_state(&state).and_then(|decision_state| decision_state.session.clone()) {+ return Some(session);+ }+ }++ {+ let mut state = state.write();+ if let Some(model_state) = state.model_state.as_mut() {+ model_state.session_state = Some(Box::new(DecisionSessionState::loading()));+ }+ }++ let engine = state.read().engine.clone();+ let session = match engine.decision(model.clone()).await {+ Ok(session) => session,+ Err(error) => {+ let mut state = state.write();+ if let Some(model_state) = state.model_state.as_mut() {+ model_state.session_state = None;+ }+ state.history.push(HistoryCellType::CommandResult {+ result: format!("Failed to load session: {}", error),+ });+ return None;+ },+ };++ {+ let mut state = state.write();+ if let Some(model_state) = state.model_state.as_mut() {+ model_state.session_state = Some(Box::new(DecisionSessionState::idle(session.clone())));+ }+ }+ Some(session)+}++// In state mode the input becomes the current state; in question mode it's a question answered for that state.+pub async fn run_session(+ state: State<ApplicationState>,+ session: DecisionSession,+ text: String,+) {+ let mut state = state;+ let text = text.trim();+ if text.is_empty() {+ return;+ }+ let current_state = decision_state(&state.read()).and_then(|decision_state| decision_state.current_state.clone());+ let Some(current_state) = current_state else {+ let mut state = state.write();+ if let Some(decision_state) = decision_state_mut(&mut state) {+ decision_state.current_state = Some(text.to_string());+ }+ state.history.push(HistoryCellType::CommandResult {+ result: "Text set, now ask questions about it".to_string(),+ });+ return;+ };++ let question = parse_question(text);+ set_status(&mut state.write(), DecisionSessionStatus::Deciding);+ let input = DecisionInput {+ state: current_state,+ questions: vec![question.clone()],+ };+ let output = session.decide(input).await;+ let mut state = state.write();+ set_status(&mut state, DecisionSessionStatus::Idle);+ match output.map(|output| output.results.into_iter().next()) {+ Ok(Some(result)) => state.history.push(HistoryCellType::DecisionOutput {+ question,+ result,+ }),+ Ok(None) => {},+ Err(DecisionSessionError::InvalidQuestion {+ message,+ ..+ }) => state.history.push(HistoryCellType::CommandResult {+ result: format!("Invalid question: {message}"),+ }),+ Err(error) => state.history.push(HistoryCellType::CommandResult {+ result: format!("Decision error: {}", error),+ }),+ }+}++pub fn is_question_mode(state: &ApplicationState) -> bool {+ decision_state(state).is_some_and(|decision_state| decision_state.current_state.is_some())+}++// Esc in question mode goes back to state mode; otherwise it's left to the application.+pub fn leave_question_mode(state: &mut ApplicationState) -> bool {+ let Some(decision_state) = decision_state_mut(state) else {+ return false;+ };+ if decision_state.status != DecisionSessionStatus::Idle || decision_state.current_state.is_none() {+ return false;+ }+ decision_state.current_state = None;+ true+}++// The first line is the instructions. No more lines make a yes/no question, one line of levels+// joined by `<` a score question, and one `key` or `key: description` per line a choice question.+// Option counts and duplicates are left to the model's prompt template, which rejects bad questions.+fn parse_question(text: &str) -> DecisionQuestion {+ let mut lines = text.lines().map(str::trim);+ let instructions = lines.next().filter(|line| !line.is_empty()).map(String::from);+ let options = lines.filter(|line| !line.is_empty()).collect::<Vec<_>>();+ match options.as_slice() {+ [] => DecisionQuestion::YesNo {+ instructions,+ no_description: None,+ yes_description: None,+ },+ [levels] if levels.contains(SCORE_LEVELS_SEPARATOR) => DecisionQuestion::Score {+ instructions,+ levels: levels.split(SCORE_LEVELS_SEPARATOR).map(|level| level.trim().to_string()).collect(),+ },+ options => DecisionQuestion::Choice {+ instructions,+ options: options+ .iter()+ .map(|option| match option.split_once(OPTION_DESCRIPTION_SEPARATOR) {+ Some((key, description)) => DecisionOption {+ key: key.trim().to_string(),+ description: Some(description.trim())+ .filter(|description| !description.is_empty())+ .map(String::from),+ },+ None => DecisionOption {+ key: option.to_string(),+ description: None,+ },+ })+ .collect(),+ },+ }+}++pub fn question_title(question: &DecisionQuestion) -> String {+ let (instructions, fallback) = match question {+ DecisionQuestion::Choice {+ instructions,+ ..+ } => (instructions, "Choice"),+ DecisionQuestion::Score {+ instructions,+ ..+ } => (instructions, "Score"),+ DecisionQuestion::YesNo {+ instructions,+ ..+ } => (instructions, "Yes or no"),+ };+ instructions.clone().unwrap_or_else(|| fallback.to_string())+}++fn set_status(+ state: &mut ApplicationState,+ status: DecisionSessionStatus,+) {+ if let Some(decision_state) = decision_state_mut(state) {+ decision_state.status = status;+ }+}++fn decision_state(state: &ApplicationState) -> Option<&DecisionSessionState> {+ state+ .model_state+ .as_ref()+ .and_then(|model_state| model_state.session_state.as_deref())+ .and_then(|session_state| session_state.as_any().downcast_ref::<DecisionSessionState>())+}++fn decision_state_mut(state: &mut ApplicationState) -> Option<&mut DecisionSessionState> {+ state+ .model_state+ .as_mut()+ .and_then(|model_state| model_state.session_state.as_deref_mut())+ .and_then(|session_state| session_state.as_any_mut().downcast_mut::<DecisionSessionState>())+}diff --git a/crates/legacy/cli/src/interactive/sessions/mod.rs b/crates/legacy/cli/src/interactive/sessions/mod.rsindex 916b7460c..eb94b8f3d 100644--- a/crates/legacy/cli/src/interactive/sessions/mod.rs+++ b/crates/legacy/cli/src/interactive/sessions/mod.rs@@ -1,5 +1,6 @@pub mod chat;pub mod classification;+pub mod decision;pub mod text_to_speech;use std::any::Any;diff --git a/crates/legacy/cli/src/server/chat_completions.rs b/crates/legacy/cli/src/server/chat_completions.rsindex e18752555..d78c6e6a3 100644--- a/crates/legacy/cli/src/server/chat_completions.rs+++ b/crates/legacy/cli/src/server/chat_completions.rs@@ -35,11 +35,18 @@ use crate::{coerce_tool_call, insert_tools_message, oai_tool_call, parse_parameter_text, reply_tool_calls,to_tool_call, tool_call_result_block, tool_parameter_types, withhold_stream_text,},+ error::{OaiError, OaiErrorResponse, strip_backend_prefixes},request_info::RequestInfo,request_log::RequestLog,},};+pub struct ChatState {+ pub session: Arc<Mutex<ChatSession>>,+ pub thinking_support: ThinkingSupport,+ pub prefix_cache: bool,+}+fn deserialize_message_content<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>whereD: serde::Deserializer<'de>,@@ -197,20 +204,6 @@ struct ChatCompletionChunk {usage: Option<ChatCompletionUsage>,}-#[derive(Serialize)]-pub struct OaiErrorResponse {- error: OaiError,-}--#[derive(Serialize)]-struct OaiError {- message: String,- #[serde(rename = "type")]- kind: String,- param: Option<String>,- code: Option<String>,-}-pub enum ChatCompletionResult {// The single JSON body arrives as a stream: Rocket only surfaces a client// disconnect by dropping the body stream, which is the blocking path's one@@ -578,16 +571,6 @@ fn usage_from_stats(}}-/// nagare re-wraps backend errors at each layer, so a message can arrive as-/// "Backend error: Backend error: ..."; the wire message keeps only the inner text.-fn strip_backend_prefixes(message: &str) -> &str {- let mut message = message;- while let Some(inner) = message.strip_prefix("Backend error: ") {- message = inner;- }- message-}-fn oai_error_body(status: Status,code: &str,@@ -1188,6 +1171,7 @@ async fn run_stream(pub async fn handle_chat_completions(body: Data<'_>,state: &State<ServerState>,+ chat: &State<ChatState>,request_info: &RequestInfo,content_type: &ContentType,) -> ChatCompletionResult {@@ -1240,7 +1224,7 @@ pub async fn handle_chat_completions(return invalid_request_response("response_format", error.code(), error.message());},};- let messages = match build_messages(&request, state.thinking_support) {+ let messages = match build_messages(&request, chat.thinking_support) {Ok(messages) => messages,Err(error) => {let param = error.param();@@ -1257,16 +1241,16 @@ pub async fn handle_chat_completions(let id = request_info.id.as_str().to_owned();if is_stream {- let session = Arc::clone(&state.session);+ let session = Arc::clone(&chat.session);let (sender, receiver) = mpsc::unbounded_channel::<Event>();tokio::spawn(- run_stream(session, messages, config, id, model, created, state.prefix_cache, parameter_types, sender, log)+ run_stream(session, messages, config, id, model, created, chat.prefix_cache, parameter_types, sender, log).in_current_span(),);let body: Pin<Box<dyn Stream<Item = Event> + Send>> = Box::pin(UnboundedReceiverStream::new(receiver));ChatCompletionResult::Stream(EventStream::from(body))} else {- let session = Arc::clone(&state.session);+ let session = Arc::clone(&chat.session);let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>();tokio::spawn(run_blocking(@@ -1276,7 +1260,7 @@ pub async fn handle_chat_completions(id,model,created,- state.prefix_cache,+ chat.prefix_cache,parameter_types,sender,log,diff --git a/crates/legacy/cli/src/server/decisions/endpoints.rs b/crates/legacy/cli/src/server/decisions/endpoints.rsnew file mode 100644index 000000000..31d026c84--- /dev/null+++ b/crates/legacy/cli/src/server/decisions/endpoints.rs@@ -0,0 +1,209 @@+use std::{sync::Arc, time::Instant};++use rocket::{+ State,+ data::{ByteUnit, Data},+ http::Status,+ post,+ response::status,+ serde::json::Json,+};+use tracing::Instrument;+use uzu::session::decision::DecisionSessionError;++use crate::server::{+ ServerState,+ decisions::{DecisionState, request::DecisionRequest, response::DecisionResponse},+ error::{OaiError, OaiErrorResponse, strip_backend_prefixes},+ request_info::RequestInfo,+};++type DecisionResult = Result<Json<DecisionResponse>, status::Custom<Json<OaiErrorResponse>>>;++// curl -s localhost:8000/v1/decisions \+// -H 'content-type: application/json' \+// -d '{+// "state": "The order arrived damaged yesterday. The customer has a receipt and asks for a replacement today.",+// "questions": {+// "route": {+// "type": "choice",+// "instructions": "Which team should handle this request?",+// "criteria": {+// "returns": "Refunds, replacements and damaged deliveries",+// "billing": "Payments, invoices and charges",+// "technical": "Product setup and faults"+// }+// },+// "receipt": {+// "type": "noul",+// "instructions": "Does the customer have a receipt?"+// },+// "urgency": {+// "type": "score",+// "instructions": "How urgent is this request?",+// "criteria": ["Routine", "Soon", "Today"]+// }+// }+// }'++// vLLM Semantic Router serves System One at both paths.+#[post("/systemone", format = "json", data = "<body>")]+#[tracing::instrument(skip_all, parent = &request_info.span)]+pub async fn handle_system_one(+ body: Data<'_>,+ state: &State<ServerState>,+ decision: &State<DecisionState>,+ request_info: &RequestInfo,+) -> DecisionResult {+ decide(body, state, decision, request_info).await+}++#[post("/decisions", format = "json", data = "<body>")]+#[tracing::instrument(skip_all, parent = &request_info.span)]+pub async fn handle_decisions(+ body: Data<'_>,+ state: &State<ServerState>,+ decision: &State<DecisionState>,+ request_info: &RequestInfo,+) -> DecisionResult {+ decide(body, state, decision, request_info).await+}++async fn decide(+ body: Data<'_>,+ state: &ServerState,+ decision: &DecisionState,+ request_info: &RequestInfo,+) -> DecisionResult {+ let body = match body.open(ByteUnit::Mebibyte(64)).into_string().await {+ Ok(body) if body.is_complete() => body.into_inner(),+ Ok(_) => {+ return Err(error_response(+ Status::BadRequest,+ Some("body"),+ "request_too_large",+ "request body exceeds 64 MiB",+ ));+ },+ Err(error) => {+ return Err(error_response(+ Status::BadRequest,+ Some("body"),+ "invalid_body",+ &format!("failed to read request body: {error}"),+ ));+ },+ };++ let log_body = serde_json::from_str::<serde_json::Value>(&body)+ .map(|value| value.to_string())+ .unwrap_or_else(|_| body.clone());+ tracing::debug!("--> {} {} body={}", request_info.method, request_info.uri, log_body);++ let request = match serde_json::from_str::<DecisionRequest>(&body) {+ Ok(request) => request,+ Err(error) => {+ tracing::info!("rejected: {error}");+ return Err(error_response(+ Status::BadRequest,+ Some("body"),+ "invalid_request",+ &format!("failed to parse System One request: {error}"),+ ));+ },+ };++ if request.questions.is_empty() {+ tracing::info!("rejected: no questions");+ return Err(error_response(+ Status::BadRequest,+ Some("questions"),+ "invalid_request",+ "questions must map one or more question ids to questions",+ ));+ }++ let (ids, input) = match request.into_input() {+ Ok(input) => input,+ Err(error) => {+ tracing::info!("rejected: question `{}`: {}", error.id, error.message);+ return Err(error_response(+ Status::BadRequest,+ Some(&format!("questions.{}", error.id)),+ "invalid_question",+ &error.message,+ ));+ },+ };++ tracing::info!("received: {} questions", ids.len());++ let started = Instant::now();+ let questions = input.questions.clone();+ let session = Arc::clone(&decision.session);+ // The lock is held by a task of its own, so a dropped request cannot release it mid-decision.+ let result = tokio::spawn(+ async move {+ let session = session.lock().await;+ session.decide(input).await+ }+ .in_current_span(),+ )+ .await;+ let elapsed = started.elapsed().as_secs_f64();++ let error = match result {+ Ok(Ok(output)) => {+ let response = DecisionResponse::new(state.model_name.clone(), ids, &questions, output);+ tracing::info!(+ "completed in {elapsed:.2}s, {} questions, prompts {} tok",+ questions.len(),+ response.usage.input_tokens+ );+ return Ok(Json(response));+ },+ Ok(Err(DecisionSessionError::InvalidQuestion {+ index,+ message,+ })) => {+ let id = &ids[index as usize];+ tracing::info!("failed in {elapsed:.2}s: question `{id}`: {message}");+ return Err(error_response(+ Status::BadRequest,+ Some(&format!("questions.{id}")),+ "invalid_question",+ &message,+ ));+ },+ Ok(Err(error)) => error.to_string(),+ Err(error) => error.to_string(),+ };++ tracing::info!("failed in {elapsed:.2}s: {error}");++ Err(error_response(Status::InternalServerError, None, "backend_error", &error))+}++fn error_response(+ status: Status,+ param: Option<&str>,+ code: &str,+ message: &str,+) -> status::Custom<Json<OaiErrorResponse>> {+ let kind = if status.code < 500 {+ "invalid_request_error"+ } else {+ "server_error"+ };+ status::Custom(+ status,+ Json(OaiErrorResponse {+ error: OaiError {+ message: strip_backend_prefixes(message).to_string(),+ kind: kind.to_string(),+ param: param.map(str::to_string),+ code: Some(code.to_string()),+ },+ }),+ )+}diff --git a/crates/legacy/cli/src/server/decisions/mod.rs b/crates/legacy/cli/src/server/decisions/mod.rsnew file mode 100644index 000000000..a2f763179--- /dev/null+++ b/crates/legacy/cli/src/server/decisions/mod.rs@@ -0,0 +1,7 @@+mod endpoints;+mod request;+mod response;+mod state;++pub use endpoints::{handle_decisions, handle_system_one};+pub use state::DecisionState;diff --git a/crates/legacy/cli/src/server/decisions/request.rs b/crates/legacy/cli/src/server/decisions/request.rsnew file mode 100644index 000000000..6043aad04--- /dev/null+++ b/crates/legacy/cli/src/server/decisions/request.rs@@ -0,0 +1,111 @@+use indexmap::IndexMap;+use serde::Deserialize;+use shoji::types::session::decision::{DecisionInput, DecisionOption, DecisionQuestion};++// The System One request of vLLM Semantic Router and d3's `d3_server.py`, text only:+// `state` must be a string and there are no `images` or `videos`.+#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct DecisionRequest {+ // Accepted and not used: replies name the served model.+ #[serde(default)]+ #[allow(dead_code)]+ pub model: Option<String>,+ #[serde(default)]+ pub state: Option<String>,+ // Raw values, so a malformed question is reported under its id.+ pub questions: IndexMap<String, serde_json::Value>,+}++#[derive(Deserialize)]+#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]+enum DecisionRequestQuestion {+ Choice {+ instructions: Option<String>,+ // Option order is answer-code order, so it must survive parsing.+ criteria: IndexMap<String, Option<String>>,+ },+ Noul {+ instructions: Option<String>,+ criteria: Option<NoulCriteria>,+ },+ Score {+ instructions: Option<String>,+ criteria: Vec<String>,+ },+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+struct NoulCriteria {+ #[serde(rename = "false")]+ no: Option<String>,+ #[serde(rename = "true")]+ yes: Option<String>,+}++impl From<DecisionRequestQuestion> for DecisionQuestion {+ fn from(question: DecisionRequestQuestion) -> Self {+ match question {+ DecisionRequestQuestion::Choice {+ instructions,+ criteria,+ } => DecisionQuestion::Choice {+ instructions,+ options: criteria+ .into_iter()+ .map(|(key, description)| DecisionOption {+ key,+ description,+ })+ .collect(),+ },+ DecisionRequestQuestion::Noul {+ instructions,+ criteria,+ } => {+ let (no_description, yes_description) =+ criteria.map_or((None, None), |criteria| (criteria.no, criteria.yes));+ DecisionQuestion::YesNo {+ instructions,+ no_description,+ yes_description,+ }+ },+ DecisionRequestQuestion::Score {+ instructions,+ criteria,+ } => DecisionQuestion::Score {+ instructions,+ levels: criteria,+ },+ }+ }+}++pub struct InvalidQuestion {+ pub id: String,+ pub message: String,+}++impl DecisionRequest {+ // The question ids in request order, and the input that decides them in the same order.+ pub fn into_input(self) -> Result<(Vec<String>, DecisionInput), InvalidQuestion> {+ let mut ids = Vec::with_capacity(self.questions.len());+ let mut questions = Vec::with_capacity(self.questions.len());+ for (id, question) in self.questions {+ let question =+ serde_json::from_value::<DecisionRequestQuestion>(question).map_err(|error| InvalidQuestion {+ id: id.clone(),+ message: error.to_string(),+ })?;+ ids.push(id);+ questions.push(question.into());+ }+ let input = DecisionInput {+ state: self.state.unwrap_or_default(),+ questions,+ };+ Ok((ids, input))+ }+}diff --git a/crates/legacy/cli/src/server/decisions/response.rs b/crates/legacy/cli/src/server/decisions/response.rsnew file mode 100644index 000000000..ec4397026--- /dev/null+++ b/crates/legacy/cli/src/server/decisions/response.rs@@ -0,0 +1,130 @@+use indexmap::IndexMap;+use serde::Serialize;+use shoji::types::session::decision::{DecisionAnswer, DecisionOutput, DecisionQuestion};++#[derive(Serialize)]+pub struct DecisionResponse {+ pub model: String,+ pub answers: IndexMap<String, DecisionResponseAnswer>,+ pub usage: DecisionResponseUsage,+}++#[derive(Serialize)]+pub struct DecisionResponseUsage {+ pub input_tokens: i64,+ pub output_tokens: i64,+}++// The answer objects of the reference `d3_runtime.product_answer`.+#[derive(Serialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum DecisionResponseAnswer {+ Choice {+ choice: String,+ probabilities: IndexMap<String, f64>,+ confidence: f64,+ },+ Noul {+ noul: f64,+ },+ Score {+ score: f64,+ // Keyed by level index, as strings.+ probabilities: IndexMap<String, f64>,+ confidence: f64,+ legend: IndexMap<String, String>,+ },+}++impl DecisionResponse {+ pub fn new(+ model: String,+ ids: Vec<String>,+ questions: &[DecisionQuestion],+ output: DecisionOutput,+ ) -> Self {+ let input_tokens = output.results.iter().map(|result| result.stats.tokens_count).sum();+ let answers = ids+ .into_iter()+ .zip(questions)+ .zip(output.results)+ .map(|((id, question), result)| (id, DecisionResponseAnswer::new(question, result.answer)))+ .collect();+ Self {+ model,+ answers,+ usage: DecisionResponseUsage {+ input_tokens,+ output_tokens: 0,+ },+ }+ }+}++impl DecisionResponseAnswer {+ fn new(+ question: &DecisionQuestion,+ answer: DecisionAnswer,+ ) -> Self {+ match (question, answer) {+ (+ DecisionQuestion::Choice {+ options,+ ..+ },+ DecisionAnswer::Choice {+ key,+ probabilities,+ ..+ },+ ) => DecisionResponseAnswer::Choice {+ choice: key,+ confidence: confidence(&probabilities),+ probabilities: options.iter().map(|option| option.key.clone()).zip(probabilities).collect(),+ },+ (+ DecisionQuestion::Score {+ levels,+ ..+ },+ DecisionAnswer::Score {+ probabilities,+ score,+ },+ ) => DecisionResponseAnswer::Score {+ score,+ confidence: confidence(&probabilities),+ probabilities: probabilities+ .into_iter()+ .enumerate()+ .map(|(index, probability)| (index.to_string(), probability))+ .collect(),+ legend: levels.iter().enumerate().map(|(index, level)| (index.to_string(), level.clone())).collect(),+ },+ (+ DecisionQuestion::YesNo {+ ..+ },+ DecisionAnswer::YesNo {+ yes_probability,+ },+ ) => DecisionResponseAnswer::Noul {+ noul: yes_probability,+ },+ _ => unreachable!("answers follow the question types"),+ }+ }+}++// One minus the normalized Shannon entropy, as the reference `d3_runtime._confidence`.+fn confidence(probabilities: &[f64]) -> f64 {+ if probabilities.len() < 2 {+ return 1.0;+ }+ let entropy = -probabilities+ .iter()+ .filter(|probability| **probability > 0.0)+ .map(|probability| probability * probability.ln())+ .sum::<f64>();+ (1.0 - entropy / (probabilities.len() as f64).ln()).clamp(0.0, 1.0)+}diff --git a/crates/legacy/cli/src/server/decisions/state.rs b/crates/legacy/cli/src/server/decisions/state.rsnew file mode 100644index 000000000..3efe7505e--- /dev/null+++ b/crates/legacy/cli/src/server/decisions/state.rs@@ -0,0 +1,9 @@+use std::sync::Arc;++use tokio::sync::Mutex;+use uzu::session::decision::DecisionSession;++pub struct DecisionState {+ // Locked for a whole request: the session refuses a second decision while one runs.+ pub session: Arc<Mutex<DecisionSession>>,+}diff --git a/crates/legacy/cli/src/server/error.rs b/crates/legacy/cli/src/server/error.rsnew file mode 100644index 000000000..d50db7f6d--- /dev/null+++ b/crates/legacy/cli/src/server/error.rs@@ -0,0 +1,25 @@+use serde::Serialize;++#[derive(Serialize)]+pub struct OaiErrorResponse {+ pub error: OaiError,+}++#[derive(Serialize)]+pub struct OaiError {+ pub message: String,+ #[serde(rename = "type")]+ pub kind: String,+ pub param: Option<String>,+ pub code: Option<String>,+}++/// nagare re-wraps backend errors at each layer, so a message can arrive as+/// "Backend error: Backend error: ..."; the wire message keeps only the inner text.+pub fn strip_backend_prefixes(message: &str) -> &str {+ let mut message = message;+ while let Some(inner) = message.strip_prefix("Backend error: ") {+ message = inner;+ }+ message+}diff --git a/crates/legacy/cli/src/server/log/mod.rs b/crates/legacy/cli/src/server/log/mod.rsindex c4dcc0643..559191575 100644--- a/crates/legacy/cli/src/server/log/mod.rs+++ b/crates/legacy/cli/src/server/log/mod.rs@@ -1,10 +1,13 @@mod file_logger;mod log_file;+mod request_logging_fairing;mod request_trace;+mod response_body_logger;use std::io;pub use file_logger::FileLogger;+pub use request_logging_fairing::RequestLoggingFairing;use tracing_subscriber::{EnvFilter, fmt::writer::MakeWriterExt, layer::SubscriberExt, util::SubscriberInitExt};use self::request_trace::{RequestContextLayer, RequestFormatter};diff --git a/crates/legacy/cli/src/server/log/request_logging_fairing.rs b/crates/legacy/cli/src/server/log/request_logging_fairing.rsnew file mode 100644index 000000000..57930e796--- /dev/null+++ b/crates/legacy/cli/src/server/log/request_logging_fairing.rs@@ -0,0 +1,48 @@+use rocket::{+ Request, Response,+ data::Data,+ fairing::{Fairing, Info, Kind},+};++use crate::server::{log::response_body_logger::ResponseBodyLogger, request_info::RequestInfo};++pub struct RequestLoggingFairing;++#[rocket::async_trait]+impl Fairing for RequestLoggingFairing {+ fn info(&self) -> Info {+ Info {+ name: "Request and response logger",+ kind: Kind::Request | Kind::Response,+ }+ }++ async fn on_request(+ &self,+ request: &mut Request<'_>,+ _data: &mut Data<'_>,+ ) {+ let _ = request.local_cache(|| RequestInfo::new(request.method(), request.uri().to_string()));+ }++ async fn on_response<'r>(+ &self,+ request: &'r Request<'_>,+ response: &mut Response<'r>,+ ) {+ if matches!(request.uri().path().as_str(), "/logs") {+ return;+ }++ let request_info = request.local_cache(|| RequestInfo::new(request.method(), request.uri().to_string()));+ let _entered = request_info.span.enter();+ let prefix = format!("<-- {} {}", response.status(), request.uri());+ if response.body().is_none() {+ tracing::debug!("{prefix} body=<empty>\n");+ } else {+ let is_json = response.content_type().is_some_and(|content_type| content_type.is_json());+ let body = response.body_mut().take();+ response.set_streamed_body(ResponseBodyLogger::new(body, prefix, is_json, request_info.span.clone()));+ }+ }+}diff --git a/crates/legacy/cli/src/server/log/response_body_logger.rs b/crates/legacy/cli/src/server/log/response_body_logger.rsnew file mode 100644index 000000000..64cba3f89--- /dev/null+++ b/crates/legacy/cli/src/server/log/response_body_logger.rs@@ -0,0 +1,86 @@+use std::{io, pin::Pin, task::Poll};++use rocket::response::Body;+use tokio::io::{AsyncRead, ReadBuf};++pub struct ResponseBodyLogger<'r> {+ body: Body<'r>,+ prefix: String,+ bytes: Vec<u8>,+ is_json: bool,+ logged: bool,+ span: tracing::Span,+}++impl<'r> ResponseBodyLogger<'r> {+ pub fn new(+ body: Body<'r>,+ prefix: String,+ is_json: bool,+ span: tracing::Span,+ ) -> Self {+ Self {+ body,+ prefix,+ bytes: Vec::new(),+ is_json,+ logged: false,+ span,+ }+ }++ fn log(+ &mut self,+ suffix: &str,+ ) {+ if self.logged {+ return;+ }+ self.logged = true;++ let body = if self.is_json {+ serde_json::from_slice::<serde_json::Value>(&self.bytes)+ .map(|value| value.to_string())+ .unwrap_or_else(|_| format!("{:?}", String::from_utf8_lossy(&self.bytes)))+ } else {+ format!("{:?}", String::from_utf8_lossy(&self.bytes))+ };+ self.span.in_scope(|| tracing::debug!("{} body={}{}\n", self.prefix, body, suffix));+ }+}++impl AsyncRead for ResponseBodyLogger<'_> {+ fn poll_read(+ self: Pin<&mut Self>,+ cx: &mut std::task::Context<'_>,+ buffer: &mut ReadBuf<'_>,+ ) -> Poll<io::Result<()>> {+ let this = self.get_mut();+ let span = this.span.clone();+ let _entered = span.enter();+ let filled_before = buffer.filled().len();++ match Pin::new(&mut this.body).poll_read(cx, buffer) {+ Poll::Ready(Ok(())) => {+ let filled_after = buffer.filled().len();+ if filled_after == filled_before {+ this.log("");+ } else {+ this.bytes.extend_from_slice(&buffer.filled()[filled_before..filled_after]);+ }+ Poll::Ready(Ok(()))+ },+ Poll::Ready(Err(error)) => {+ this.log(" [read error]");+ Poll::Ready(Err(error))+ },+ Poll::Pending => Poll::Pending,+ }+ }+}++impl Drop for ResponseBodyLogger<'_> {+ fn drop(&mut self) {+ self.log(" [incomplete]");+ }+}diff --git a/crates/legacy/cli/src/server/mod.rs b/crates/legacy/cli/src/server/mod.rsindex ed97ac331..e29c99a3e 100644--- a/crates/legacy/cli/src/server/mod.rs+++ b/crates/legacy/cli/src/server/mod.rs@@ -1,14 +1,17 @@+mod error;mod log;mod request_info;pub mod chat_completions;pub mod chat_tool_calls;+pub mod decisions;pub mod models;pub mod request_log;pub mod runner;pub mod state;-pub use chat_completions::handle_chat_completions;+pub use chat_completions::{ChatState, handle_chat_completions};+pub use decisions::{DecisionState, handle_decisions, handle_system_one};pub use models::handle_models;pub use runner::run_server;pub use state::ServerState;diff --git a/crates/legacy/cli/src/server/runner.rs b/crates/legacy/cli/src/server/runner.rsindex 5148fdcf9..32ec25982 100644--- a/crates/legacy/cli/src/server/runner.rs+++ b/crates/legacy/cli/src/server/runner.rs@@ -1,156 +1,23 @@-use std::{io, net::IpAddr, path::PathBuf, pin::Pin, sync::Arc, task::Poll, time::Duration};+use std::{net::IpAddr, path::PathBuf, sync::Arc, time::Duration};use anyhow::{Context, Result, bail};use indicatif::{ProgressBar, ProgressStyle};-use rocket::{- Config, Request, Response,- config::LogLevel,- data::Data,- fairing::{Fairing, Info, Kind},- response::Body,- routes,-};-use tokio::{- io::{AsyncRead, ReadBuf},- sync::Mutex,-};+use rocket::{Config, config::LogLevel, routes};+use tokio::sync::Mutex;use uzu::{engine::{Engine, EngineConfig},- types::session::chat::ChatConfig,+ types::{model::ModelSpecialization, session::chat::ChatConfig},};use crate::{common::thinking::ThinkingSupport,server::{- ServerState, handle_chat_completions, handle_models,- log::{self, FileLogger},- request_info::RequestInfo,+ ChatState, DecisionState, ServerState, handle_chat_completions, handle_decisions, handle_models,+ handle_system_one,+ log::{self, FileLogger, RequestLoggingFairing},},};-pub struct ResponseBodyLogger<'r> {- body: Body<'r>,- prefix: String,- bytes: Vec<u8>,- is_json: bool,- logged: bool,- span: tracing::Span,-}--impl<'r> ResponseBodyLogger<'r> {- pub fn new(- body: Body<'r>,- prefix: String,- is_json: bool,- span: tracing::Span,- ) -> Self {- Self {- body,- prefix,- bytes: Vec::new(),- is_json,- logged: false,- span,- }- }-- fn log(- &mut self,- suffix: &str,- ) {- if self.logged {- return;- }- self.logged = true;-- let body = if self.is_json {- serde_json::from_slice::<serde_json::Value>(&self.bytes)- .map(|value| value.to_string())- .unwrap_or_else(|_| format!("{:?}", String::from_utf8_lossy(&self.bytes)))- } else {- format!("{:?}", String::from_utf8_lossy(&self.bytes))- };- self.span.in_scope(|| tracing::debug!("{} body={}{}\n", self.prefix, body, suffix));- }-}--impl AsyncRead for ResponseBodyLogger<'_> {- fn poll_read(- self: Pin<&mut Self>,- cx: &mut std::task::Context<'_>,- buffer: &mut ReadBuf<'_>,- ) -> Poll<io::Result<()>> {- let this = self.get_mut();- let span = this.span.clone();- let _entered = span.enter();- let filled_before = buffer.filled().len();-- match Pin::new(&mut this.body).poll_read(cx, buffer) {- Poll::Ready(Ok(())) => {- let filled_after = buffer.filled().len();- if filled_after == filled_before {- this.log("");- } else {- this.bytes.extend_from_slice(&buffer.filled()[filled_before..filled_after]);- }- Poll::Ready(Ok(()))- },- Poll::Ready(Err(error)) => {- this.log(" [read error]");- Poll::Ready(Err(error))- },- Poll::Pending => Poll::Pending,- }- }-}--impl Drop for ResponseBodyLogger<'_> {- fn drop(&mut self) {- self.log(" [incomplete]");- }-}--struct RequestLoggingFairing;--#[rocket::async_trait]-impl Fairing for RequestLoggingFairing {- fn info(&self) -> Info {- Info {- name: "Request and response logger",- kind: Kind::Request | Kind::Response,- }- }-- async fn on_request(- &self,- request: &mut Request<'_>,- _data: &mut Data<'_>,- ) {- let _ = request.local_cache(|| RequestInfo::new(request.method(), request.uri().to_string()));- }-- async fn on_response<'r>(- &self,- request: &'r Request<'_>,- response: &mut Response<'r>,- ) {- if matches!(request.uri().path().as_str(), "/logs") {- return;- }-- let request_info = request.local_cache(|| RequestInfo::new(request.method(), request.uri().to_string()));- let _entered = request_info.span.enter();- let prefix = format!("<-- {} {}", response.status(), request.uri());- if response.body().is_none() {- tracing::debug!("{prefix} body=<empty>\n");- } else {- let is_json = response.content_type().is_some_and(|content_type| content_type.is_json());- let body = response.body_mut().take();- response.set_streamed_body(ResponseBodyLogger::new(body, prefix, is_json, request_info.span.clone()));- }- }-}-pub async fn run_server(model: String,host: String,@@ -186,17 +53,7 @@ pub async fn run_server(}spinner.finish_with_message(format!("Loaded: {}", resolved.identifier));- let thinking_support = ThinkingSupport::for_model(&resolved);- let session =- engine.chat(resolved.clone(), ChatConfig::default()).await.context("Failed to create chat session")?;let model_name = resolved.identifier.clone();- let state = ServerState {- model_name: model_name.clone(),- session: Arc::new(Mutex::new(session)),- thinking_support,- prefix_cache,- };-let address: IpAddr = host.parse().with_context(|| format!("Invalid host: {host}"))?;let config = Config {port,@@ -205,36 +62,69 @@ pub async fn run_server(..Config::default()};- let prefix_cache_enabled = if prefix_cache {- "enabled"+ let rocket = rocket::custom(config)+ .manage(ServerState {+ model_name: model_name.clone(),+ })+ .attach(RequestLoggingFairing);++ let (rocket, title, details) = if resolved.specializations.contains(&ModelSpecialization::Decision {}) {+ let session = engine.decision(resolved).await.context("Failed to create decision session")?;+ let state = DecisionState {+ session: Arc::new(Mutex::new(session)),+ };+ let rocket = rocket+ .manage(state)+ .mount("/", routes![handle_system_one, handle_decisions, handle_models])+ .mount("/v1", routes![handle_system_one, handle_decisions, handle_models]);+ let details = "📝 Endpoints:\n POST /v1/systemone (or /v1/decisions, /systemone, /decisions)\n";+ (rocket, "System One server", details.to_string())} else {- "disabled"+ let thinking_support = ThinkingSupport::for_model(&resolved);+ let session = engine.chat(resolved, ChatConfig::default()).await.context("Failed to create chat session")?;+ let state = ChatState {+ session: Arc::new(Mutex::new(session)),+ thinking_support,+ prefix_cache,+ };+ let rocket = rocket+ .manage(state)+ .mount("/", routes![handle_chat_completions, handle_models])+ .mount("/v1", routes![handle_chat_completions, handle_models]);+ let prefix_cache_enabled = if prefix_cache {+ "enabled"+ } else {+ "disabled"+ };+ let details = format!(+ concat!(+ "🗄️ Prefix cache: {prefix_cache_enabled}\n",+ "📝 Endpoints:\n",+ " POST /v1/chat/completions (or /chat/completions)\n",+ ),+ prefix_cache_enabled = prefix_cache_enabled,+ );+ (rocket, "OpenAI-compatible server", details)};+if let Some(ref file_logger) = file_logger {tracing::info!("🗃️ Logs will be written to file: {}", file_logger.file_path().display())}tracing::info!(concat!(- "🚀 OpenAI-compatible server v{version} for model: {model_name}\n",+ "🚀 {title} v{version} for model: {model_name}\n","🌐 Available at: http://{host}:{port}\n",- "🗄️ Prefix cache: {prefix_cache_enabled}\n",- "📝 Endpoints:\n",- " POST /v1/chat/completions (or /chat/completions)\n",+ "{details}"," GET /v1/models (or /models)\n",),+ title = title,version = Engine::version(),model_name = model_name,host = host,port = port,- prefix_cache_enabled = prefix_cache_enabled,+ details = details,);- let rocket = rocket::custom(config)- .manage(state)- .attach(RequestLoggingFairing)- .mount("/", routes![handle_chat_completions, handle_models])- .mount("/v1", routes![handle_chat_completions, handle_models]);-if let Err(error) = rocket.launch().await {bail!("Server error: {error}");}diff --git a/crates/legacy/cli/src/server/state.rs b/crates/legacy/cli/src/server/state.rsindex a6fbd3d7d..302f9401b 100644--- a/crates/legacy/cli/src/server/state.rs+++ b/crates/legacy/cli/src/server/state.rs@@ -1,13 +1,3 @@-use std::sync::Arc;--use tokio::sync::Mutex;-use uzu::session::chat::ChatSession;--use crate::common::thinking::ThinkingSupport;-pub struct ServerState {pub model_name: String,- pub session: Arc<Mutex<ChatSession>>,- pub thinking_support: ThinkingSupport,- pub prefix_cache: bool,}diff --git a/crates/legacy/uzu/src/storage/model_tasks.rs b/crates/legacy/uzu/src/storage/model_tasks.rsindex e022a4685..272dc2520 100644--- a/crates/legacy/uzu/src/storage/model_tasks.rs+++ b/crates/legacy/uzu/src/storage/model_tasks.rs@@ -60,6 +60,9 @@ impl ModelTask {match initialized {Ok(task) => {let mut progress = task.progress();+ // `progress` only reports changes, and an already downloaded model has none:+ // announce the state that replaces `Initializing`.+ let _ = events.send((identifier.clone(), task.state()));while let Some(state) = progress.next().await {let _ = events.send((identifier.clone(), state));}