Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): write compaction summaries on smol_model when set (#9252)
Akarshan Biswas2ff2c4f4f982
diff --git a/docs/src/pages/docs/agent/context.mdx b/docs/src/pages/docs/agent/context.mdxindex 311a23745..b48dcff5a 100644--- a/docs/src/pages/docs/agent/context.mdx+++ b/docs/src/pages/docs/agent/context.mdx@@ -172,6 +172,12 @@ name = "small-window"compaction_ratio = 0.6```+The summary is written by `smol_model` from `~/.jan/config.toml` when one is set, so the session's+own model is not spent on condensing its history. If the smol model fails (its smaller window+overflows, it is unreachable, or it returns nothing), the session's model writes the summary+instead. A run under a `[budget]` money limit always summarizes on its own model, so every request+is charged at the rates the limit was priced against.+The check runs on the request itself, before it is dispatched, so the break lands at a point thesession chose rather than after a provider rejects an oversized prompt and the run retries. When itruns, the session history is replaced with the compacted version, the transcript is told, and thediff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rsindex d89f0f94c..a34fa972e 100644--- a/src-tauri/src/core/agent/compaction.rs+++ b/src-tauri/src/core/agent/compaction.rs@@ -469,27 +469,33 @@ async fn summarize(if transcript.trim().is_empty() {return Ok((FALLBACK_NOTE.to_string(), None));}- let request = json!({- "model": model_id,- "messages": [- { "role": "system", "content": SUMMARY_SYSTEM_PROMPT },- { "role": "user", "content": transcript },- ],- });- // Discard the summarizer's streamed tokens: a dropped receiver means these- // never reach the user-facing event stream.- let (sink, _rx) = mpsc::unbounded_channel();- match model.invoke(&request, &sink).await {- Ok(completion) => {- let summary = extract_choice_message(&completion)- .and_then(|m| m.get("content"))- .and_then(|c| c.as_str())- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string);- // Charged whatever the body said: a completion whose text was empty- // still cost what the provider reported for it.- let usage = crate::core::agent::events::Usage::from_completion(&completion);+ // The smol model writes the summary when one is configured: summarizing is+ // the cheap model's job. Any failure there, an overflow of its smaller+ // window included, falls back to the run's own model rather than to a+ // note, so a misconfigured smol model never costs the user their history.+ // An empty smol reply was still billed: its usage rides along with the+ // retry's so the run's budget is charged for both requests.+ let mut smol_usage = None;+ if let Some((smol_id, smol)) = model.summarizer() {+ match request_summary(&transcript, smol_id, smol).await {+ Ok((Some(summary), usage)) => return Ok((summary, usage)),+ Ok((None, usage)) => {+ smol_usage = usage;+ log::warn!(+ "agent: compaction summary from {smol_id} was empty, retrying on {model_id}"+ );+ }+ Err(e) => log::warn!(+ "agent: compaction summary from {smol_id} failed, retrying on {model_id}: {e}"+ ),+ }+ }+ match request_summary(&transcript, model_id, model).await {+ Ok((summary, usage)) => {+ let usage = match (smol_usage, usage) {+ (Some(smol), Some(run)) => Some(smol.plus(&run)),+ (smol, run) => smol.or(run),+ };Ok((summary.unwrap_or_else(|| FALLBACK_NOTE.to_string()), usage))}Err(e) => {@@ -499,12 +505,42 @@ async fn summarize(if crate::core::agent::upstream::is_context_overflow_error(&e) {Err(e)} else {- Ok((FALLBACK_NOTE.to_string(), None))+ Ok((FALLBACK_NOTE.to_string(), smol_usage))}}}}+/// One summarizer request for an already rendered `transcript`: the summary+/// text (`None` when the completion carried none) and the reported usage.+async fn request_summary(+ transcript: &str,+ model_id: &str,+ model: &dyn ModelInvoker,+) -> Result<(Option<String>, Option<crate::core::agent::events::Usage>), String> {+ let request = json!({+ "model": model_id,+ "messages": [+ { "role": "system", "content": SUMMARY_SYSTEM_PROMPT },+ { "role": "user", "content": transcript },+ ],+ });+ // Discard the summarizer's streamed tokens: a dropped receiver means these+ // never reach the user-facing event stream.+ let (sink, _rx) = mpsc::unbounded_channel();+ let completion = model.invoke(&request, &sink).await?;+ let summary = extract_choice_message(&completion)+ .and_then(|m| m.get("content"))+ .and_then(|c| c.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string);+ // Charged whatever the body said: a completion whose text was empty still+ // cost what the provider reported for it.+ let usage = crate::core::agent::events::Usage::from_completion(&completion);+ Ok((summary, usage))+}+#[cfg(test)]mod tests {use super::*;@@ -853,6 +889,101 @@ mod tests {assert!(crate::core::agent::upstream::is_context_overflow_error(&error));}+ /// A run model whose summaries go to a configured smol model first.+ struct WithSmol<M, S> {+ run: M,+ smol: S,+ }+ #[async_trait]+ impl<M: ModelInvoker, S: ModelInvoker> ModelInvoker for WithSmol<M, S> {+ async fn invoke(+ &self,+ request: &Value,+ events: &mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ ) -> Result<Value, String> {+ self.run.invoke(request, events).await+ }+ fn summarizer(&self) -> Option<(&str, &dyn ModelInvoker)> {+ Some(("smol", &self.smol))+ }+ }++ fn stub(summary: &str) -> StubModel {+ StubModel {+ summary: summary.into(),+ calls: StdMutex::new(0),+ requests: tokio::sync::Mutex::new(Vec::new()),+ }+ }++ /// With a smol model configured the summary is its job: the run's model is+ /// never called, and the request names the smol model's id.+ #[tokio::test]+ async fn a_configured_smol_model_writes_the_summary() {+ let model = WithSmol { run: stub("RUN"), smol: stub("SMOL") };+ let out = compact_conversation(&convo(20), "m", &model, 4).await.unwrap();+ assert!(out[1]["content"].as_str().unwrap().contains("SMOL"));+ assert_eq!(*model.run.calls.lock().unwrap(), 0);+ assert_eq!(model.smol.requests.lock().await[0]["model"], "smol");+ }++ /// A smol model that fails, by overflowing its smaller window or otherwise,+ /// or answers nothing, hands the summary back to the run's model instead+ /// of costing the history a fallback note or the request an error.+ #[tokio::test]+ async fn a_failing_smol_model_falls_back_to_the_run_model() {+ let overflowing = WithSmol { run: stub("RUN"), smol: OverflowingModel };+ let failing = WithSmol { run: stub("RUN"), smol: FailingModel };+ let empty = WithSmol { run: stub("RUN"), smol: stub(" ") };+ for out in [+ compact_conversation(&convo(20), "m", &overflowing, 4).await,+ compact_conversation(&convo(20), "m", &failing, 4).await,+ compact_conversation(&convo(20), "m", &empty, 4).await,+ ] {+ assert!(out.unwrap()[1]["content"].as_str().unwrap().contains("RUN"));+ }+ let requests = overflowing.run.requests.lock().await;+ assert_eq!(requests[0]["model"], "m", "the retry is on the run's own model");+ }++ /// A model answering `content` and reporting `prompt`/`completion` tokens.+ struct Billed(&'static str, u64, u64);+ #[async_trait]+ impl ModelInvoker for Billed {+ async fn invoke(+ &self,+ _request: &Value,+ _events: &mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ ) -> Result<Value, String> {+ Ok(json!({+ "choices": [{ "message": { "content": self.0 } }],+ "usage": {+ "prompt_tokens": self.1,+ "completion_tokens": self.2,+ "total_tokens": self.1 + self.2,+ },+ }))+ }+ }++ /// An empty smol reply was still billed, so its usage is charged along+ /// with the run model's retry rather than dropped with the empty text.+ #[tokio::test]+ async fn an_empty_smol_reply_is_still_charged() {+ let model = WithSmol { run: Billed("RUN", 1_000, 50), smol: Billed(" ", 900, 7) };+ let (_, usage) = summarize_span(&convo(20)[1..17], "m", &model).await.unwrap();+ let usage = usage.expect("both requests reported usage");+ assert_eq!(usage.prompt_tokens, Some(1_900));+ assert_eq!(usage.completion_tokens, Some(57));+ assert_eq!(usage.total_tokens, Some(1_957));++ // Still charged when the run model's retry then fails into the note.+ let model = WithSmol { run: FailingModel, smol: Billed("", 900, 7) };+ let (note, usage) = summarize_span(&convo(20)[1..17], "m", &model).await.unwrap();+ assert!(note["content"].as_str().unwrap().contains(FALLBACK_NOTE));+ assert_eq!(usage.expect("the smol request was billed").completion_tokens, Some(7));+ }+/// One prompt driving a long agentic run is the normal shape here: a single/// user message followed by hundreds of assistant/tool rounds. Compaction/// has to bite into that from the top, or the run it was called to rescuediff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex 1a171a4b1..fa21a2397 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -512,6 +512,22 @@ impl Usage {cache_write_tokens,})}++ /// Two requests' usage as one charge: each count is the sum of whatever+ /// either side reported, and stays `None` only when neither reported it.+ pub(crate) fn plus(&self, other: &Self) -> Self {+ let sum = |a: Option<u64>, b: Option<u64>| match (a, b) {+ (None, None) => None,+ (a, b) => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))),+ };+ Self {+ prompt_tokens: sum(self.prompt_tokens, other.prompt_tokens),+ completion_tokens: sum(self.completion_tokens, other.completion_tokens),+ total_tokens: sum(self.total_tokens, other.total_tokens),+ cached_tokens: sum(self.cached_tokens, other.cached_tokens),+ cache_write_tokens: sum(self.cache_write_tokens, other.cache_write_tokens),+ }+ }}/// Test-only, and reachable from the sibling test in `core::cli::run_report`diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex 854878e8e..d9fc40668 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -16,9 +16,9 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# agent.toml [provider] section (~/.jan/projects/<project>/agent.toml).## default_model = "my-model" # used when no --model / agent.toml model is set-# smol_model = "my-fast-model" # fast model for the `smol` role (/goal evaluation and-# # subagents with model = "smol"); defaults to the-# # session's model when unset+# smol_model = "my-fast-model" # fast model for the `smol` role (/goal evaluation,+# # compaction summaries and subagents with+# # model = "smol"); defaults to the session's model# mouse = false # disable TUI mouse tracking (scroll wheel,# # click-to-expand); on by default# sandbox = true # run `shell` under OS confinement (same as@@ -105,8 +105,8 @@ struct GlobalConfigToml {/// flag nor `agent.toml` names one. Takes precedence over any derived guess.#[serde(default, skip_serializing_if = "Option::is_none")]default_model: Option<String>,- /// Fast, cheap model for the `smol` role: goal evaluation and other- /// lightweight side calls. Falls back to `default_model` when unset.+ /// Fast, cheap model for the `smol` role: goal evaluation, compaction+ /// summaries and other lightweight side calls. Falls back to `default_model` when unset.#[serde(default, skip_serializing_if = "Option::is_none")]smol_model: Option<String>,/// TUI mouse tracking (wheel scrolling, click-to-expand). `None` = thediff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 6e57e81db..68bbc81eb 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -214,6 +214,14 @@ pub(crate) trait ModelInvoker: Send + Sync {request: &serde_json::Value,events: &mpsc::UnboundedSender<StreamEvent>,) -> Result<serde_json::Value, String>;++ /// The model id and invoker that write this run's compaction summaries in+ /// its place, or `None` to summarize on the run's own model. Set to the+ /// `smol` role model when one is configured: condensing a transcript does+ /// not need the run's model, and it is the largest side request a run makes.+ fn summarizer(&self) -> Option<(&str, &dyn ModelInvoker)> {+ None+ }}/// One tool call's outcome: `content` is the model-facing result string,@@ -467,6 +475,9 @@ struct HttpModelInvoker {/// just before it leaves, and the completion is mapped back. `None` = off,/// and then nothing in the request or the reply changes.secrets: Option<Arc<crate::core::agent::secrets::SecretFilter>>,+ /// The `smol` model's id and invoker, which compaction summaries go to+ /// first (see [`ModelInvoker::summarizer`]). `None` summarizes on this one.+ summarizer: Option<Box<(String, HttpModelInvoker)>>,}/// [`crate::core::agent::provenance::RequestIdentity`] as the invoker stores it:@@ -537,6 +548,12 @@ fn converter_http_client() -> reqwest::Client {#[async_trait]impl ModelInvoker for HttpModelInvoker {+ fn summarizer(&self) -> Option<(&str, &dyn ModelInvoker)> {+ self.summarizer+ .as_deref()+ .map(|(id, model)| (id.as_str(), model as &dyn ModelInvoker))+ }+async fn invoke(&self,request: &serde_json::Value,@@ -3690,6 +3707,7 @@ async fn orchestrate_inner(.await?;let max_turns = body_turn_cap(json_body);+ let cost_ceiling = body_cost_ceiling(json_body);let provenance = request_identity(&model_id, provider_configs, run_id.as_deref()).await;let converter = provenance@@ -3711,6 +3729,13 @@ async fn orchestrate_inner(provenance,provenance_events: Some(events.clone()),secrets: crate::core::agent::secrets::for_run(),+ // A metered run charges every side request at its own model's rates, so+ // a summary billed on another model would be costed at a price nobody+ // quoted for it: under a money ceiling the run summarizes on itself.+ summarizer: match cost_ceiling {+ Some(_) => None,+ None => smol_summarizer(args, &model_id, Some(events.clone())).await,+ },};let mcp_tools = McpToolInvoker {tool_to_server,@@ -3719,7 +3744,6 @@ async fn orchestrate_inner(};let max_session_tokens = body_session_budget(json_body);- let cost_ceiling = body_cost_ceiling(json_body);let mut budget = SessionBudget::new(max_session_tokens).with_cost_ceiling(cost_ceiling);if let Some(root) = project_root {@@ -4148,42 +4172,11 @@ pub(crate) async fn compact_history(.with_hooks(&hooks, false, None);crate::core::agent::compaction::fire_pre_compact(&hooks, &ctx, messages.len()).await;}- let (upstream_url, api_keys) = resolve_upstream_for_model(- model_id,- args.provider_configs.clone(),- #[cfg(not(feature = "cli"))]- args.llama_state.clone(),- #[cfg(not(feature = "cli"))]- args.mlx_sessions.clone(),- )- .await?;- let provenance =- request_identity(model_id, &args.provider_configs, args.run_id.as_deref()).await;- let converter = provenance- .api_type- .as_deref()- .and_then(|api_type| converter_for(Some(api_type), provenance.oauth));- let model = HttpModelInvoker {- client: args.client.clone(),- upstream_url,- api_keys,- provider_configs: args.provider_configs.clone(),- converter,- converter_client: converter_http_client(),- // A compaction call is billed to the same session as the turn that- // triggered it, so it carries the same correlation id: leaving it out- // would make the session's recorded spend smaller than the bill.- client_request_id: crate::core::agent::correlation::session_request_id(- args.session_id.as_deref(),- ),- session_id: args.session_id.clone(),- provenance,- // A `/compact` runs between turns: there is no run stream in existence- // to carry the record, so this request is reported nowhere rather than- // somewhere a client cannot read.- provenance_events: None,- secrets: crate::core::agent::secrets::for_run(),- };+ // A `/compact` runs between turns: there is no run stream in existence to+ // carry the provenance record, so this request is reported nowhere rather+ // than somewhere a client cannot read.+ let mut model = side_call_invoker(args, model_id, None).await?;+ model.summarizer = smol_summarizer(args, model_id, None).await;crate::core::agent::compaction::compact_conversation(messages, model_id, &model, keep_recent).await}@@ -4199,7 +4192,7 @@ pub(crate) async fn evaluate_goal(condition: &str,messages: &[serde_json::Value],) -> Result<crate::core::agent::goal::GoalVerdict, String> {- let model = side_call_invoker(args, smol_model_id).await?;+ let model = side_call_invoker(args, smol_model_id, None).await?;crate::core::agent::goal::evaluate(smol_model_id, condition, messages, &model).await}@@ -4213,7 +4206,7 @@ pub(crate) async fn side_completion(model_id: &str,request: &serde_json::Value,) -> Result<String, String> {- let model = side_call_invoker(args, model_id).await?;+ let model = side_call_invoker(args, model_id, None).await?;// Nothing streams to the user: a dropped receiver keeps the tokens internal.let (sink, _rx) = mpsc::unbounded_channel();let completion = model.invoke(request, &sink).await?;@@ -4224,12 +4217,34 @@ pub(crate) async fn side_completion(.to_string())}-/// The invoker a between-turns side call uses: `model_id`'s upstream, billed to-/// this session, with no run stream to report provenance on.-#[cfg(feature = "cli")]+/// The `smol` model's invoker for compaction summaries, or `None` when no smol+/// model is configured, it is `model_id` itself, or it cannot be resolved (the+/// summary then goes to `model_id`, which is what it did before smol existed).+async fn smol_summarizer(+ args: &OrchestrationArgs,+ model_id: &str,+ provenance_events: Option<mpsc::UnboundedSender<StreamEvent>>,+) -> Option<Box<(String, HttpModelInvoker)>> {+ let smol = crate::core::agent::subagent::configured_smol_model()?;+ if smol == model_id {+ return None;+ }+ match side_call_invoker(args, &smol, provenance_events).await {+ Ok(model) => Some(Box::new((smol, model))),+ Err(e) => {+ log::warn!("agent: smol_model {smol} cannot summarize, compacting on {model_id}: {e}");+ None+ }+ }+}++/// The invoker a side call uses: `model_id`'s upstream, billed to this session.+/// `provenance_events` is the run stream its provenance rides, `None` between+/// turns where no run stream exists.async fn side_call_invoker(args: &OrchestrationArgs,smol_model_id: &str,+ provenance_events: Option<mpsc::UnboundedSender<StreamEvent>>,) -> Result<HttpModelInvoker, String> {let (upstream_url, api_keys) = resolve_upstream_for_model(smol_model_id,@@ -4257,15 +4272,17 @@ async fn side_call_invoker(provider_configs: args.provider_configs.clone(),converter,converter_client: converter_http_client(),- // Same session, same bill (see `compact_history`).+ // A side call is billed to the same session as the turn it serves, so+ // it carries the same correlation id: leaving it out would make the+ // session's recorded spend smaller than the bill.client_request_id: crate::core::agent::correlation::session_request_id(args.session_id.as_deref(),),session_id: args.session_id.clone(),provenance,- // Between turns, like `/compact`: no run stream exists to carry it.- provenance_events: None,+ provenance_events,secrets: crate::core::agent::secrets::for_run(),+ summarizer: None,};Ok(model)}@@ -5598,6 +5615,7 @@ mod tests {},provenance_events: Some(run),secrets: None,+ summarizer: None,};let request =@@ -5690,6 +5708,7 @@ mod tests {},provenance_events: None,secrets: Some(filter),+ summarizer: None,};let request = json!({"model":"m","messages":[{"role":"user","content":format!("my key is {SECRET}")}]});@@ -5778,6 +5797,7 @@ mod tests {provenance: RequestIdentityOwned::default(),provenance_events: Some(run),secrets: None,+ summarizer: None,};let (tx, _rx) = mpsc::unbounded_channel();invokerdiff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex f6607cb37..db39f700a 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -16666,7 +16666,7 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[AgentSettingDef {key: SMOL_MODEL_KEY,label: "smol_model",- desc: "cheap model for subagents with model = \"smol\" and /goal checks",+ desc: "cheap model for subagents with model = \"smol\", /goal checks and compaction",// Unset falls back to the session's model; there is no fixed id to show.kind: AgentSettingKind::Text {default: "the main model",