Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

cli model settings

eugene3ba03a0a2b52
diff --git a/crates/hanashi/src/chat/harmony/bridging/message.rs b/crates/hanashi/src/chat/harmony/bridging/message.rs
index 351965c24..1aab9633a 100644
--- a/crates/hanashi/src/chat/harmony/bridging/message.rs
+++ b/crates/hanashi/src/chat/harmony/bridging/message.rs
@@ -42,7 +42,7 @@ pub fn bridge_messages_to_harmony(messages: &[ChatMessage]) -> Result<Vec<Extern
value,
} => {
system_filled = true;
- system_content.reasoning_effort = Some(value.clone().to_harmony()?);
+ system_content.reasoning_effort = Some((*value).to_harmony()?);
},
ChatContentBlock::ConversationStartDate {
value,
diff --git a/crates/shoji/src/types/basic/reasoning_effort.rs b/crates/shoji/src/types/basic/reasoning_effort.rs
index 01246f04a..6b8e75725 100644
--- a/crates/shoji/src/types/basic/reasoning_effort.rs
+++ b/crates/shoji/src/types/basic/reasoning_effort.rs
@@ -6,7 +6,7 @@ use std::{
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
#[bindings::export(Enumeration)]
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReasoningEffort {
Disabled,
Default,
diff --git a/crates/uzu/src/cli/components/application.rs b/crates/uzu/src/cli/components/application.rs
index 3b772023e..54b5eb7c1 100644
--- a/crates/uzu/src/cli/components/application.rs
+++ b/crates/uzu/src/cli/components/application.rs
@@ -3,8 +3,10 @@ use shoji::types::model::Model;
use crate::{
cli::{
- components::{CommandInput, HistoryCell, HistoryCellType, Logo, SelectedModel, Theme},
- flows::{AuthFlow, ExitFlow, Flow, FlowEvent, FlowRegistry, ModelRegistriesFlow, ThemeFlow},
+ components::{
+ CommandInput, HistoryCell, HistoryCellType, Logo, ModelCapabilities, Preferences, SelectedModel, Theme,
+ },
+ flows::{AuthFlow, ExitFlow, Flow, FlowEvent, FlowRegistry, ModelRegistriesFlow, SettingsFlow, ThemeFlow},
helpers::SYMBOL_COMMAND,
sessions::{self, SessionState},
},
@@ -20,6 +22,7 @@ pub struct ApplicationProps {
pub engine: Option<Engine>,
pub settings: Option<Settings>,
pub theme: Option<Theme>,
+ pub preferences: Option<Preferences>,
pub model: Option<String>,
}
@@ -27,12 +30,14 @@ pub struct ModelState {
pub model: Model,
pub download_state: DownloadState,
pub session_state: Option<Box<dyn SessionState>>,
+ pub capabilities: ModelCapabilities,
}
pub struct ApplicationState {
pub engine: Engine,
pub settings: Option<Settings>,
pub theme: Theme,
+ pub preferences: Preferences,
pub flow: Option<Box<dyn Flow>>,
pub history: Vec<HistoryCellType>,
pub registry: FlowRegistry,
@@ -56,13 +61,15 @@ pub fn Application(
engine,
settings: props.settings.clone(),
theme: props.theme.clone().unwrap_or_default(),
+ preferences: props.preferences.unwrap_or_default(),
flow: None,
history: Vec::new(),
registry: FlowRegistry::default()
- .register("auth", "Add models from a specific provider", || Box::new(AuthFlow))
- .register("theme", "Choose the theme", || Box::new(ThemeFlow))
- .register("model", "Choose the model", || Box::new(ModelRegistriesFlow))
- .register("exit", "Exit the CLI", || Box::new(ExitFlow)),
+ .register("auth", "Add models from a specific provider", false, || Box::new(AuthFlow))
+ .register("model", "Choose the model", false, || Box::new(ModelRegistriesFlow))
+ .register("settings", "Configure thinking and sampling", true, || Box::new(SettingsFlow))
+ .register("theme", "Choose the theme", false, || Box::new(ThemeFlow))
+ .register("exit", "Exit the CLI", false, || Box::new(ExitFlow)),
model_state: None,
});
let (width, _) = hooks.use_terminal_size();
@@ -82,6 +89,7 @@ pub fn Application(
model,
download_state: DownloadState::not_downloaded(0),
session_state: None,
+ capabilities: ModelCapabilities::default(),
});
state.write().history.push(HistoryCellType::CommandResult {
result: summary,
@@ -105,8 +113,14 @@ pub fn Application(
name: name.to_string(),
});
let registry = state.read().registry.clone();
- match registry.create(name) {
- Some(flow) => state.write().flow = Some(flow),
+ let model_loaded = state.read().model_state.is_some();
+ match registry.command(name) {
+ Some(command) if command.requires_model && !model_loaded => {
+ state.write().history.push(HistoryCellType::CommandResult {
+ result: "Load a model first to open settings".to_string(),
+ })
+ },
+ Some(command) => state.write().flow = Some((command.factory)()),
None => state.write().history.push(HistoryCellType::CommandResult {
result: format!("Unknown command: /{}", name),
}),
diff --git a/crates/uzu/src/cli/components/command_input.rs b/crates/uzu/src/cli/components/command_input.rs
index 73a83a3ce..3cb92fc44 100644
--- a/crates/uzu/src/cli/components/command_input.rs
+++ b/crates/uzu/src/cli/components/command_input.rs
@@ -86,7 +86,15 @@ fn valid_commands(
let Some(command_name) = input.strip_prefix(SYMBOL_COMMAND) else {
return Vec::new();
};
- state.read().registry.commands().into_iter().filter(|command| command.name.starts_with(command_name)).collect()
+ let model_loaded = state.read().model_state.is_some();
+ state
+ .read()
+ .registry
+ .commands()
+ .into_iter()
+ .filter(|command| command.name.starts_with(command_name))
+ .filter(|command| !command.requires_model || model_loaded)
+ .collect()
}
fn hint_component(
diff --git a/crates/uzu/src/cli/components/mod.rs b/crates/uzu/src/cli/components/mod.rs
index 7462670b9..de5d2a049 100644
--- a/crates/uzu/src/cli/components/mod.rs
+++ b/crates/uzu/src/cli/components/mod.rs
@@ -4,6 +4,8 @@ mod gradient;
mod history_cell;
mod loading;
mod logo;
+mod model_capabilities;
+mod preferences;
mod progress_bar;
mod rendered_text;
mod selected_model;
@@ -17,6 +19,8 @@ pub use gradient::Gradient;
pub use history_cell::{HistoryCell, HistoryCellType};
pub use loading::Loading;
pub use logo::Logo;
+pub use model_capabilities::{ModelCapabilities, ModelSamplingDefaults, ThinkingSupport};
+pub use preferences::{Preferences, SamplingMode};
pub use progress_bar::ProgressBar;
pub use rendered_text::RenderedText;
pub use selected_model::SelectedModel;
diff --git a/crates/uzu/src/cli/components/model_capabilities.rs b/crates/uzu/src/cli/components/model_capabilities.rs
new file mode 100644
index 000000000..9efcb9d02
--- /dev/null
+++ b/crates/uzu/src/cli/components/model_capabilities.rs
@@ -0,0 +1,178 @@
+use std::path::Path;
+
+use serde_json::Value;
+use shoji::types::{basic::ReasoningEffort, model::Model};
+
+use super::preferences::{ThinkingPreference, cycle};
+use crate::engine::Engine;
+
+const LEVELS: [ReasoningEffort; 5] = [
+ ReasoningEffort::Default,
+ ReasoningEffort::Low,
+ ReasoningEffort::Medium,
+ ReasoningEffort::High,
+ ReasoningEffort::Disabled,
+];
+
+fn level_label(effort: ReasoningEffort) -> &'static str {
+ match effort {
+ ReasoningEffort::Default => "model default",
+ ReasoningEffort::Low => "low",
+ ReasoningEffort::Medium => "medium",
+ ReasoningEffort::High => "high",
+ ReasoningEffort::Disabled => "off",
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ThinkingSupport {
+ Levels(ReasoningEffort),
+ Toggle(bool),
+ AlwaysOn,
+ #[default]
+ Unsupported,
+}
+
+impl ThinkingSupport {
+ pub fn is_adjustable(self) -> bool {
+ matches!(self, Self::Levels(_) | Self::Toggle(_))
+ }
+
+ pub fn with_preference(
+ self,
+ preference: &ThinkingPreference,
+ ) -> Self {
+ match self {
+ Self::Levels(_) => Self::Levels(preference.level),
+ Self::Toggle(_) => Self::Toggle(preference.enabled),
+ other => other,
+ }
+ }
+
+ pub fn cycled(
+ self,
+ delta: i64,
+ ) -> Self {
+ match self {
+ Self::Levels(effort) => Self::Levels(cycle(&LEVELS, effort, delta as isize)),
+ Self::Toggle(value) => Self::Toggle(!value),
+ other => other,
+ }
+ }
+
+ pub fn write_back(
+ self,
+ preference: &mut ThinkingPreference,
+ ) {
+ match self {
+ Self::Levels(effort) => preference.level = effort,
+ Self::Toggle(value) => preference.enabled = value,
+ Self::AlwaysOn | Self::Unsupported => {},
+ }
+ }
+
+ pub fn value_label(self) -> &'static str {
+ match self {
+ Self::Levels(effort) => level_label(effort),
+ Self::Toggle(true) => "on",
+ Self::Toggle(false) => "off",
+ Self::AlwaysOn => "always on",
+ Self::Unsupported => "not supported",
+ }
+ }
+
+ pub fn reasoning_effort(self) -> Option<ReasoningEffort> {
+ match self {
+ Self::Levels(ReasoningEffort::Default) | Self::Toggle(true) => None,
+ Self::Levels(effort) => Some(effort),
+ Self::Toggle(false) => Some(ReasoningEffort::Disabled),
+ Self::AlwaysOn | Self::Unsupported => None,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Default)]
+pub struct ModelSamplingDefaults {
+ pub temperature: Option<f64>,
+ pub top_k: Option<i64>,
+ pub top_p: Option<f64>,
+ pub min_p: Option<f64>,
+}
+
+impl ModelSamplingDefaults {
+ pub fn summary(&self) -> String {
+ let mut parts = Vec::new();
+ if let Some(value) = self.temperature {
+ parts.push(format!("temp {value:.2}"));
+ }
+ if let Some(value) = self.top_k {
+ parts.push(format!("top-k {value}"));
+ }
+ if let Some(value) = self.top_p {
+ parts.push(format!("top-p {value:.2}"));
+ }
+ if let Some(value) = self.min_p {
+ parts.push(format!("min-p {value:.2}"));
+ }
+ if parts.is_empty() {
+ "model defaults".to_string()
+ } else {
+ parts.join(", ")
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Default)]
+pub struct ModelCapabilities {
+ pub thinking: ThinkingSupport,
+ pub sampling_defaults: ModelSamplingDefaults,
+}
+
+impl ModelCapabilities {
+ pub async fn load(
+ engine: &Engine,
+ model: &Model,
+ ) -> Self {
+ if model.is_remote() {
+ return Self {
+ thinking: ThinkingSupport::Levels(ReasoningEffort::Default),
+ sampling_defaults: ModelSamplingDefaults::default(),
+ };
+ }
+ let Some(path) = engine.model_path(model).await else {
+ return Self::default();
+ };
+ let raw = tokio::fs::read_to_string(Path::new(&path).join("config.json")).await.ok();
+ raw.and_then(|raw| Self::from_config(&raw)).unwrap_or_default()
+ }
+
+ fn from_config(raw: &str) -> Option<Self> {
+ let json: Value = serde_json::from_str(raw).ok()?;
+
+ let codec = json.get("token_codec_config");
+ let template = codec.and_then(|codec| codec.get("prompt_template")).and_then(Value::as_str).unwrap_or_default();
+ let emits_reasoning =
+ codec.and_then(|codec| codec.get("output_parser_regex")).map(|value| !value.is_null()).unwrap_or(false);
+ let thinking = if template.contains("enable_thinking") {
+ ThinkingSupport::Toggle(true)
+ } else if emits_reasoning {
+ ThinkingSupport::AlwaysOn
+ } else {
+ ThinkingSupport::Unsupported
+ };
+
+ let generation = json.get("generation_config");
+ let field = |key: &str| generation.and_then(|generation| generation.get(key));
+ let sampling_defaults = ModelSamplingDefaults {
+ temperature: field("temperature").and_then(Value::as_f64),
+ top_k: field("top_k").and_then(Value::as_i64),
+ top_p: field("top_p").and_then(Value::as_f64),
+ min_p: field("min_p").and_then(Value::as_f64),
+ };
+
+ Some(Self {
+ thinking,
+ sampling_defaults,
+ })
+ }
+}
diff --git a/crates/uzu/src/cli/components/preferences.rs b/crates/uzu/src/cli/components/preferences.rs
new file mode 100644
index 000000000..9983d59fc
--- /dev/null
+++ b/crates/uzu/src/cli/components/preferences.rs
@@ -0,0 +1,168 @@
+use serde::{Deserialize, Serialize};
+use shoji::types::basic::{ReasoningEffort, SamplingMethod, SamplingPolicy};
+
+use crate::settings::{SettingKind, Settings, SettingsError};
+
+const SETTINGS_PREFERENCES: &str = "cli_preferences";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct ThinkingPreference {
+ pub level: ReasoningEffort,
+ pub enabled: bool,
+}
+
+impl Default for ThinkingPreference {
+ fn default() -> Self {
+ Self {
+ level: ReasoningEffort::Default,
+ enabled: true,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum SamplingMode {
+ #[default]
+ ModelDefault,
+ Greedy,
+ Stochastic,
+}
+
+impl SamplingMode {
+ pub const ALL: [SamplingMode; 3] = [Self::ModelDefault, Self::Greedy, Self::Stochastic];
+
+ pub fn label(&self) -> &'static str {
+ match self {
+ Self::ModelDefault => "model default",
+ Self::Greedy => "greedy",
+ Self::Stochastic => "stochastic",
+ }
+ }
+
+ pub fn next(self) -> Self {
+ cycle(&Self::ALL, self, 1)
+ }
+
+ pub fn previous(self) -> Self {
+ cycle(&Self::ALL, self, -1)
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct SamplingPreferences {
+ pub mode: SamplingMode,
+ pub temperature_enabled: bool,
+ pub temperature: f64,
+ pub top_k_enabled: bool,
+ pub top_k: i64,
+ pub top_p_enabled: bool,
+ pub top_p: f64,
+ pub min_p_enabled: bool,
+ pub min_p: f64,
+}
+
+impl Default for SamplingPreferences {
+ fn default() -> Self {
+ Self {
+ mode: SamplingMode::default(),
+ temperature_enabled: false,
+ temperature: 0.8,
+ top_k_enabled: false,
+ top_k: 64,
+ top_p_enabled: false,
+ top_p: 0.95,
+ min_p_enabled: false,
+ min_p: 0.05,
+ }
+ }
+}
+
+impl SamplingPreferences {
+ pub fn policy(&self) -> SamplingPolicy {
+ match self.mode {
+ SamplingMode::ModelDefault => SamplingPolicy::Default {},
+ SamplingMode::Greedy => SamplingPolicy::Custom {
+ method: SamplingMethod::Greedy {},
+ },
+ SamplingMode::Stochastic => SamplingPolicy::Custom {
+ method: SamplingMethod::Stochastic {
+ temperature: self.temperature_enabled.then_some(self.temperature),
+ top_k: self.top_k_enabled.then_some(self.top_k),
+ top_p: self.top_p_enabled.then_some(self.top_p),
+ min_p: self.min_p_enabled.then_some(self.min_p),
+ },
+ },
+ }
+ }
+
+ pub fn summary(&self) -> String {
+ match self.mode {
+ SamplingMode::ModelDefault => "default".to_string(),
+ SamplingMode::Greedy => "greedy".to_string(),
+ SamplingMode::Stochastic => {
+ let mut parts = Vec::new();
+ if self.temperature_enabled {
+ parts.push(format!("temp {:.2}", self.temperature));
+ }
+ if self.top_k_enabled {
+ parts.push(format!("top-k {}", self.top_k));
+ }
+ if self.top_p_enabled {
+ parts.push(format!("top-p {:.2}", self.top_p));
+ }
+ if self.min_p_enabled {
+ parts.push(format!("min-p {:.2}", self.min_p));
+ }
+ if parts.is_empty() {
+ "stochastic".to_string()
+ } else {
+ parts.join(", ")
+ }
+ },
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
+#[serde(default)]
+pub struct Preferences {
+ pub thinking: ThinkingPreference,
+ pub sampling: SamplingPreferences,
+}
+
+impl Preferences {
+ pub fn load(settings: &Settings) -> Result<Self, SettingsError> {
+ let Some(raw) = settings.load(SettingKind::Config, SETTINGS_PREFERENCES.to_string())? else {
+ return Ok(Self::default());
+ };
+ Ok(serde_json::from_str(&raw).unwrap_or_default())
+ }
+
+ pub fn save(
+ &self,
+ settings: &Settings,
+ ) -> Result<(), SettingsError> {
+ let raw = serde_json::to_string(self).map_err(|error| SettingsError::BackendError {
+ message: error.to_string(),
+ })?;
+ settings.save(SettingKind::Config, SETTINGS_PREFERENCES.to_string(), Some(raw))
+ }
+
+ pub fn sampling_policy(&self) -> SamplingPolicy {
+ self.sampling.policy()
+ }
+}
+
+pub(super) fn cycle<T: Copy + PartialEq>(
+ values: &[T],
+ current: T,
+ delta: isize,
+) -> T {
+ let length = values.len() as isize;
+ let index = values.iter().position(|value| *value == current).map(|index| index as isize).unwrap_or(0);
+ let next = (index + delta).rem_euclid(length) as usize;
+ values[next]
+}
diff --git a/crates/uzu/src/cli/components/selected_model.rs b/crates/uzu/src/cli/components/selected_model.rs
index 94fb44c86..224e7f312 100644
--- a/crates/uzu/src/cli/components/selected_model.rs
+++ b/crates/uzu/src/cli/components/selected_model.rs
@@ -4,7 +4,7 @@ use iocraft::prelude::*;
use tokio_stream::StreamExt;
use crate::{
- cli::components::{ApplicationState, ProgressBar},
+ cli::components::{ApplicationState, ModelCapabilities, ProgressBar, ThinkingSupport},
storage::types::DownloadPhase,
};
@@ -34,6 +34,10 @@ pub fn SelectedModel(
let Some(model) = model else {
return;
};
+ let capabilities = ModelCapabilities::load(&engine, &model).await;
+ if let Some(model_state) = state.write().model_state.as_mut() {
+ model_state.capabilities = capabilities;
+ }
if !model.is_downloadable() {
return;
}
@@ -42,10 +46,12 @@ pub fn SelectedModel(
let mut stream = engine.storage_subscribe().await;
- if let Some(initial) = downloader.state().await
- && let Some(model_state) = state.write().model_state.as_mut()
- {
- model_state.download_state = initial;
+ let mut was_downloaded = false;
+ if let Some(initial) = downloader.state().await {
+ was_downloaded = matches!(initial.phase, DownloadPhase::Downloaded {});
+ if let Some(model_state) = state.write().model_state.as_mut() {
+ model_state.download_state = initial;
+ }
}
if downloader.resume().await.is_err() {
@@ -69,9 +75,17 @@ pub fn SelectedModel(
last_progress_rendered_at = None;
}
+ let became_downloaded = !was_downloaded && matches!(event_state.phase, DownloadPhase::Downloaded {});
+ was_downloaded = matches!(event_state.phase, DownloadPhase::Downloaded {});
if let Some(model_state) = state.write().model_state.as_mut() {
model_state.download_state = event_state;
}
+ if became_downloaded {
+ let capabilities = ModelCapabilities::load(&engine, &model).await;
+ if let Some(model_state) = state.write().model_state.as_mut() {
+ model_state.capabilities = capabilities;
+ }
+ }
}
}
});
@@ -153,14 +167,15 @@ pub fn SelectedModel(
});
let theme = state.read().theme.clone();
+ let preferences = state.read().preferences;
let model_data = state.read().model_state.as_ref().map(|model_state| {
let session_status = model_state.session_state.as_deref().and_then(|session_state| session_state.status_text());
- (model_state.model.clone(), model_state.download_state.clone(), session_status)
+ (model_state.model.clone(), model_state.download_state.clone(), session_status, model_state.capabilities)
});
let view: AnyElement<'static> = match model_data {
None => element! { View }.into(),
- Some((model, download_state, session_status)) => {
+ Some((model, download_state, session_status, capabilities)) => {
let is_downloaded = matches!(download_state.phase, DownloadPhase::Downloaded {});
let is_downloading = matches!(download_state.phase, DownloadPhase::Downloading {});
let status = if is_downloading {
@@ -184,6 +199,16 @@ pub fn SelectedModel(
);
let padding = theme.padding();
let padding_wide = theme.padding_wide();
+ let chat_indicator = (model.is_chat_capable() && (is_downloaded || !model.is_downloadable())).then(|| {
+ let thinking = match capabilities.thinking.with_preference(&preferences.thinking) {
+ ThinkingSupport::Unsupported => None,
+ support => Some(support.value_label()),
+ };
+ match thinking {
+ Some(thinking) => format!("think {} · {}", thinking, preferences.sampling.mode.label()),
+ None => format!("sampling {}", preferences.sampling.mode.label()),
+ }
+ });
element! {
View(
@@ -209,6 +234,12 @@ pub fn SelectedModel(
#((!is_downloading).then(|| element! {
View(flex_grow: 1.0f32)
}))
+ #(chat_indicator.map(|indicator| element! {
+ View(flex_direction: FlexDirection::Row) {
+ Text(content: indicator, color: theme.subtitle_color)
+ View(width: padding_wide as u32)
+ }
+ }))
#(session_status.map(|status| element! {
Text(content: status, color: theme.subtitle_color)
}))
diff --git a/crates/uzu/src/cli/flows/mod.rs b/crates/uzu/src/cli/flows/mod.rs
index b8869b2b2..7a35fcc1f 100644
--- a/crates/uzu/src/cli/flows/mod.rs
+++ b/crates/uzu/src/cli/flows/mod.rs
@@ -5,6 +5,7 @@ mod model_families;
mod model_registries;
mod models;
mod registry;
+mod settings;
mod theme;
pub use auth::AuthFlow;
@@ -14,6 +15,7 @@ pub use model_families::ModelFamiliesFlow;
pub use model_registries::ModelRegistriesFlow;
pub use models::ModelsFlow;
pub use registry::{Command, FlowRegistry};
+pub use settings::SettingsFlow;
pub use theme::ThemeFlow;
pub struct FlowEvent {
diff --git a/crates/uzu/src/cli/flows/models.rs b/crates/uzu/src/cli/flows/models.rs
index fdfd52688..fbd6663ac 100644
--- a/crates/uzu/src/cli/flows/models.rs
+++ b/crates/uzu/src/cli/flows/models.rs
@@ -5,7 +5,7 @@ use shoji::types::model::Model;
use crate::{
cli::{
- components::{ApplicationState, Loading, ModelState, Selector, SelectorItem, SelectorStyle},
+ components::{ApplicationState, Loading, ModelCapabilities, ModelState, Selector, SelectorItem, SelectorStyle},
flows::{Flow, FlowEvent},
},
storage::types::DownloadState,
@@ -115,6 +115,7 @@ fn Models(
model: model.clone(),
download_state: DownloadState::not_downloaded(0),
session_state: None,
+ capabilities: ModelCapabilities::default(),
});
on_event(FlowEvent::finish(summary));
}
diff --git a/crates/uzu/src/cli/flows/registry.rs b/crates/uzu/src/cli/flows/registry.rs
index f1c62bf7e..d7baab425 100644
--- a/crates/uzu/src/cli/flows/registry.rs
+++ b/crates/uzu/src/cli/flows/registry.rs
@@ -8,6 +8,7 @@ pub type FlowFactory = Arc<dyn Fn() -> Box<dyn Flow> + Send + Sync>;
pub struct Command {
pub name: String,
pub description: String,
+ pub requires_model: bool,
pub factory: FlowFactory,
}
@@ -21,6 +22,7 @@ impl FlowRegistry {
mut self,
name: impl Into<String>,
description: impl Into<String>,
+ requires_model: bool,
factory: F,
) -> Self
where
@@ -30,17 +32,18 @@ impl FlowRegistry {
let command = Command {
name: name.clone(),
description: description.into(),
+ requires_model,
factory: Arc::new(factory),
};
self.commands.insert(name, command);
self
}
- pub fn create(
+ pub fn command(
&self,
name: &str,
- ) -> Option<Box<dyn Flow>> {
- self.commands.get(name).map(|command| (command.factory)())
+ ) -> Option<Command> {
+ self.commands.get(name).cloned()
}
pub fn commands(&self) -> Vec<Command> {
diff --git a/crates/uzu/src/cli/flows/settings.rs b/crates/uzu/src/cli/flows/settings.rs
new file mode 100644
index 000000000..e0125cf2d
--- /dev/null
+++ b/crates/uzu/src/cli/flows/settings.rs
@@ -0,0 +1,444 @@
+use iocraft::prelude::*;
+
+use crate::cli::{
+ components::{ApplicationState, ModelSamplingDefaults, Preferences, SamplingMode, Theme, ThinkingSupport},
+ flows::{Flow, FlowEvent},
+};
+
+const LABEL_WIDTH: u16 = 14;
+const TEMPERATURE_STEP: f64 = 0.05;
+const TEMPERATURE_MAX: f64 = 2.0;
+const PROBABILITY_STEP: f64 = 0.05;
+const PROBABILITY_MAX: f64 = 1.0;
+const TOP_K_STEP: i64 = 1;
+const TOP_K_MIN: i64 = 1;
+const TOP_K_MAX: i64 = 4096;
+
+pub struct SettingsFlow;
+
+impl Flow for SettingsFlow {
+ fn render(
+ &self,
+ on_event: Handler<FlowEvent>,
+ ) -> AnyElement<'static> {
+ element! { SettingsFlowView(on_event: on_event) }.into()
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Field {
+ Thinking,
+ SamplingMode,
+ Temperature,
+ TopK,
+ TopP,
+ MinP,
+}
+
+fn visible_fields(
+ preferences: &Preferences,
+ support: ThinkingSupport,
+) -> Vec<Field> {
+ let mut fields = Vec::new();
+ if support.is_adjustable() {
+ fields.push(Field::Thinking);
+ }
+ fields.push(Field::SamplingMode);
+ if preferences.sampling.mode == SamplingMode::Stochastic {
+ fields.extend([Field::Temperature, Field::TopK, Field::TopP, Field::MinP]);
+ }
+ fields
+}
+
+fn adjust(
+ preferences: &mut Preferences,
+ field: Field,
+ delta: i64,
+ support: ThinkingSupport,
+) {
+ match field {
+ Field::Thinking => {
+ support.with_preference(&preferences.thinking).cycled(delta).write_back(&mut preferences.thinking);
+ },
+ Field::SamplingMode => {
+ preferences.sampling.mode = if delta >= 0 {
+ preferences.sampling.mode.next()
+ } else {
+ preferences.sampling.mode.previous()
+ };
+ },
+ Field::Temperature => {
+ preferences.sampling.temperature =
+ step_f64(preferences.sampling.temperature, delta, TEMPERATURE_STEP, 0.0, TEMPERATURE_MAX);
+ },
+ Field::TopK => {
+ preferences.sampling.top_k = (preferences.sampling.top_k + delta * TOP_K_STEP).clamp(TOP_K_MIN, TOP_K_MAX);
+ },
+ Field::TopP => {
+ preferences.sampling.top_p =
+ step_f64(preferences.sampling.top_p, delta, PROBABILITY_STEP, 0.0, PROBABILITY_MAX);
+ },
+ Field::MinP => {
+ preferences.sampling.min_p =
+ step_f64(preferences.sampling.min_p, delta, PROBABILITY_STEP, 0.0, PROBABILITY_MAX);
+ },
+ }
+}
+
+fn toggle(
+ preferences: &mut Preferences,
+ field: Field,
+ support: ThinkingSupport,
+) {
+ match field {
+ Field::Thinking => adjust(preferences, Field::Thinking, 1, support),
+ Field::SamplingMode => preferences.sampling.mode = preferences.sampling.mode.next(),
+ Field::Temperature => preferences.sampling.temperature_enabled = !preferences.sampling.temperature_enabled,
+ Field::TopK => preferences.sampling.top_k_enabled = !preferences.sampling.top_k_enabled,
+ Field::TopP => preferences.sampling.top_p_enabled = !preferences.sampling.top_p_enabled,
+ Field::MinP => preferences.sampling.min_p_enabled = !preferences.sampling.min_p_enabled,
+ }
+}
+
+fn step_f64(
+ value: f64,
+ delta: i64,
+ step: f64,
+ min: f64,
+ max: f64,
+) -> f64 {
+ let next = (value + delta as f64 * step).clamp(min, max);
+ (next * 100.0).round() / 100.0
+}
+
+fn float_value(
+ enabled: bool,
+ value: f64,
+ default: Option<f64>,
+) -> String {
+ if enabled {
+ format!("{value:.2}")
+ } else {
+ default.map(|value| format!("{value:.2}")).unwrap_or_else(|| "—".to_string())
+ }
+}
+
+fn int_value(
+ enabled: bool,
+ value: i64,
+ default: Option<i64>,
+) -> String {
+ if enabled {
+ value.to_string()
+ } else {
+ default.map(|value| value.to_string()).unwrap_or_else(|| "—".to_string())
+ }
+}
+
+#[derive(Default, Props)]
+pub struct SettingsFlowViewProps {
+ pub on_event: Handler<FlowEvent>,
+}
+
+#[component]
+fn SettingsFlowView(
+ props: &mut SettingsFlowViewProps,
+ mut hooks: Hooks,
+) -> impl Into<AnyElement<'static>> {
+ let on_event = std::mem::take(&mut props.on_event);
+ let state = *hooks.use_context::<State<ApplicationState>>();
+
+ let capabilities =
+ state.read().model_state.as_ref().map(|model_state| model_state.capabilities).unwrap_or_default();
+ let support = capabilities.thinking;
+ let defaults = capabilities.sampling_defaults;
+
+ let mut draft = hooks.use_state(|| state.read().preferences);
+ let mut selected_index = hooks.use_state(|| 0usize);
+
+ let preferences = draft.get();
+ let fields = visible_fields(&preferences, support);
+ if selected_index.get() >= fields.len() {
+ selected_index.set(fields.len().saturating_sub(1));
+ }
+
+ hooks.use_terminal_events(move |event| {
+ let TerminalEvent::Key(KeyEvent {
+ code,
+ kind,
+ ..
+ }) = event
+ else {
+ return;
+ };
+ if kind == KeyEventKind::Release {
+ return;
+ }
+
+ let preferences = draft.get();
+ let fields = visible_fields(&preferences, support);
+ if fields.is_empty() {
+ return;
+ }
+ let current = selected_index.get().min(fields.len() - 1);
+ let field = fields[current];
+
+ match code {
+ KeyCode::Up => {
+ let next = if current == 0 {
+ fields.len() - 1
+ } else {
+ current - 1
+ };
+ selected_index.set(next);
+ },
+ KeyCode::Down => {
+ let next = if current + 1 >= fields.len() {
+ 0
+ } else {
+ current + 1
+ };
+ selected_index.set(next);
+ },
+ KeyCode::Left => {
+ let mut preferences = draft.get();
+ adjust(&mut preferences, field, -1, support);
+ draft.set(preferences);
+ },
+ KeyCode::Right => {
+ let mut preferences = draft.get();
+ adjust(&mut preferences, field, 1, support);
+ draft.set(preferences);
+ },
+ KeyCode::Char(' ') => {
+ let mut preferences = draft.get();
+ toggle(&mut preferences, field, support);
+ draft.set(preferences);
+ },
+ KeyCode::Enter => {
+ let mut state = state;
+ let preferences = draft.get();
+ let summary = format!(
+ "thinking {} · sampling {}",
+ thinking_summary(support, &preferences),
+ preferences.sampling.summary()
+ );
+ let result = match state.read().settings.clone() {
+ Some(settings) => match preferences.save(&settings) {
+ Ok(()) => format!("Settings saved ({})", summary),
+ Err(error) => format!("Settings applied ({}), unable to save: {}", summary, error),
+ },
+ None => format!("Settings applied ({})", summary),
+ };
+ state.write().preferences = preferences;
+ on_event(FlowEvent::finish(result));
+ },
+ _ => {},
+ }
+ });
+
+ let theme = state.read().theme.clone();
+ let selected = fields.get(selected_index.get().min(fields.len().saturating_sub(1))).copied();
+ let padding = theme.padding();
+
+ let mut rows: Vec<AnyElement<'static>> = vec![section_header("Thinking", &theme)];
+ if support.is_adjustable() {
+ rows.push(field_row(Field::Thinking, &preferences, selected, &theme, support, defaults));
+ } else {
+ rows.push(info_row("Thinking", support.value_label(), &theme));
+ }
+
+ rows.push(section_header("Sampling", &theme));
+ rows.push(field_row(Field::SamplingMode, &preferences, selected, &theme, support, defaults));
+ match preferences.sampling.mode {
+ SamplingMode::ModelDefault => rows.push(info_row("", &format!("uses {}", defaults.summary()), &theme)),
+ SamplingMode::Greedy => {},
+ SamplingMode::Stochastic => {
+ rows.push(field_row(Field::Temperature, &preferences, selected, &theme, support, defaults));
+ rows.push(field_row(Field::TopK, &preferences, selected, &theme, support, defaults));
+ rows.push(field_row(Field::TopP, &preferences, selected, &theme, support, defaults));
+ rows.push(field_row(Field::MinP, &preferences, selected, &theme, support, defaults));
+ },
+ }
+
+ element! {
+ View(flex_direction: FlexDirection::Column, padding_left: padding, padding_right: padding) {
+ #(rows.into_iter())
+ View(height: padding)
+ Text(
+ content: "↑↓ move · ←→ adjust · space toggle · enter save · esc cancel",
+ color: theme.subtitle_color,
+ )
+ }
+ }
+}
+
+fn thinking_summary(
+ support: ThinkingSupport,
+ preferences: &Preferences,
+) -> &'static str {
+ support.with_preference(&preferences.thinking).value_label()
+}
+
+fn section_header(
+ title: &str,
+ theme: &Theme,
+) -> AnyElement<'static> {
+ element! {
+ View(margin_top: 1) {
+ Text(content: title.to_string(), color: Some(theme.accent_color), weight: Weight::Bold)
+ }
+ }
+ .into()
+}
+
+fn info_row(
+ label: &str,
+ value: &str,
+ theme: &Theme,
+) -> AnyElement<'static> {
+ element! {
+ View(flex_direction: FlexDirection::Row, column_gap: 1u16) {
+ Text(content: " ", color: Some(theme.subtitle_color))
+ View(width: LABEL_WIDTH) {
+ Text(content: label.to_string(), color: Some(theme.subtitle_color))
+ }
+ Text(content: value.to_string(), color: Some(theme.subtitle_color))
+ }
+ }
+ .into()
+}
+
+fn field_row(
+ field: Field,
+ preferences: &Preferences,
+ selected: Option<Field>,
+ theme: &Theme,
+ support: ThinkingSupport,
+ defaults: ModelSamplingDefaults,
+) -> AnyElement<'static> {
+ let is_selected = selected == Some(field);
+ let marker = if is_selected {
+ "›"
+ } else {
+ " "
+ };
+ let value_color = if is_selected {
+ Some(theme.accent_color)
+ } else {
+ None
+ };
+
+ let (label, control): (&str, AnyElement<'static>) = match field {
+ Field::Thinking => (
+ "Thinking",
+ cycle_control(support.with_preference(&preferences.thinking).value_label(), value_color, theme),
+ ),
+ Field::SamplingMode => ("Sampling", cycle_control(preferences.sampling.mode.label(), value_color, theme)),
+ Field::Temperature => (
+ "Temperature",
+ toggle_control(
+ preferences.sampling.temperature_enabled,
+ float_value(
+ preferences.sampling.temperature_enabled,
+ preferences.sampling.temperature,
+ defaults.temperature,
+ ),
+ is_selected,
+ theme,
+ ),
+ ),
+ Field::TopK => (
+ "Top K",
+ toggle_control(
+ preferences.sampling.top_k_enabled,
+ int_value(preferences.sampling.top_k_enabled, preferences.sampling.top_k, defaults.top_k),
+ is_selected,
+ theme,
+ ),
+ ),
+ Field::TopP => (
+ "Top P",
+ toggle_control(
+ preferences.sampling.top_p_enabled,
+ float_value(preferences.sampling.top_p_enabled, preferences.sampling.top_p, defaults.top_p),
+ is_selected,
+ theme,
+ ),
+ ),
+ Field::MinP => (
+ "Min P",
+ toggle_control(
+ preferences.sampling.min_p_enabled,
+ float_value(preferences.sampling.min_p_enabled, preferences.sampling.min_p, defaults.min_p),
+ is_selected,
+ theme,
+ ),
+ ),
+ };
+
+ element! {
+ View(flex_direction: FlexDirection::Row, column_gap: 1u16) {
+ Text(content: marker, color: Some(theme.accent_color))
+ View(width: LABEL_WIDTH) {
+ Text(
+ content: label.to_string(),
+ color: if is_selected { Some(theme.accent_color) } else { None },
+ )
+ }
+ #(control)
+ }
+ }
+ .into()
+}
+
+fn cycle_control(
+ value: &str,
+ value_color: Option<Color>,
+ theme: &Theme,
+) -> AnyElement<'static> {
+ element! {
+ View(flex_direction: FlexDirection::Row) {
+ Text(content: "‹ ", color: Some(theme.subtitle_color))
+ Text(content: value.to_string(), color: value_color, weight: Weight::Bold)
+ Text(content: " ›", color: Some(theme.subtitle_color))
+ }
+ }
+ .into()
+}
+
+fn toggle_control(
+ enabled: bool,
+ value: String,
+ is_selected: bool,
+ theme: &Theme,
+) -> AnyElement<'static> {
+ let checkbox = if enabled {
+ "[x]"
+ } else {
+ "[ ]"
+ };
+ let checkbox_color = if enabled {
+ Some(theme.accent_color)
+ } else {
+ Some(theme.subtitle_color)
+ };
+ let value_color = if is_selected {
+ Some(theme.accent_color)
+ } else if enabled {
+ None
+ } else {
+ Some(theme.subtitle_color)
+ };
+ let hint: Option<AnyElement<'static>> =
+ (!enabled).then(|| element! { Text(content: "(default)", color: Some(theme.subtitle_color)) }.into());
+
+ element! {
+ View(flex_direction: FlexDirection::Row, column_gap: 1u16) {
+ Text(content: checkbox, color: checkbox_color)
+ Text(content: value, color: value_color, weight: Weight::Bold)
+ #(hint.into_iter())
+ }
+ }
+ .into()
+}
diff --git a/crates/uzu/src/cli/mod.rs b/crates/uzu/src/cli/mod.rs
index e6d8af222..d16c3806d 100644
--- a/crates/uzu/src/cli/mod.rs
+++ b/crates/uzu/src/cli/mod.rs
@@ -5,7 +5,7 @@ mod sessions;
use std::io::IsTerminal;
-use components::{Application, Theme};
+use components::{Application, Preferences, Theme};
use iocraft::prelude::*;
use crate::{
@@ -55,9 +55,19 @@ impl CliApplication {
Some(settings) => Theme::load(settings)?.unwrap_or_default(),
None => Theme::default(),
};
+ let preferences = match &settings {
+ Some(settings) => Preferences::load(settings)?,
+ None => Preferences::default(),
+ };
element! {
- Application(engine: Some(self.engine.clone()), settings: settings, theme: Some(theme), model: model)
+ Application(
+ engine: Some(self.engine.clone()),
+ settings: settings,
+ theme: Some(theme),
+ preferences: Some(preferences),
+ model: model,
+ )
}
.render_loop()
.await
diff --git a/crates/uzu/src/cli/sessions/chat.rs b/crates/uzu/src/cli/sessions/chat.rs
index a184ed2f4..a09c31b0a 100644
--- a/crates/uzu/src/cli/sessions/chat.rs
+++ b/crates/uzu/src/cli/sessions/chat.rs
@@ -135,7 +135,14 @@ pub async fn run_session(
text: String,
) {
let mut state = state;
- let user_message = ChatMessage::user().with_text(text);
+ let preferences = state.read().preferences;
+ let thinking_support =
+ state.read().model_state.as_ref().map(|model_state| model_state.capabilities.thinking).unwrap_or_default();
+ let mut user_message = ChatMessage::user().with_text(text);
+ if let Some(reasoning_effort) = thinking_support.with_preference(&preferences.thinking).reasoning_effort() {
+ user_message = user_message.with_reasoning_effort(reasoning_effort);
+ }
+ let reply_config = ChatReplyConfig::default().with_sampling_policy(preferences.sampling_policy());
{
let mut state = state.write();
if let Some(chat_state) = chat_state_mut(&mut state) {
@@ -145,7 +152,7 @@ pub async fn run_session(
}
}
- let stream = session.reply_with_stream(vec![user_message], ChatReplyConfig::default()).await;
+ let stream = session.reply_with_stream(vec![user_message], reply_config).await;
let mut latest_reply: Option<ChatReply> = None;
{
let mut state = state.write();