diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index fbe7053bd2..9dbc63b201 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -676,6 +676,17 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen } let pictures = ask_pictures(args)?; eprintln!("[{} ยท {}]", cfg.provider, cfg.model); + // A level asked for that the model doesn't take isn't sent: said. + if cfg.login() && cfg.reasoning != Some(false) && !cfg.effort.trim().is_empty() && cfg.effort.trim() != cfg.effort_sent() { + let mark = s.notice_mark(); + s.notify( + format!("the effort {:?} isn't among those listed for {}; {} is used", cfg.effort.trim(), cfg.model, cfg.effort_sent()), + false, + ); + for n in s.notices_since(mark) { + eprintln!("rustgis-cli: {}", n.text); + } + } let yes = args.iter().any(|a| a == "--yes"); let trace_key = cfg.key.clone(); let mut a = Agent::new(cfg, s); @@ -719,6 +730,10 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen allow }); show(&a); + if let Some(u) = a.usage() { + let least = if u.partial { "at least " } else { "" }; + eprintln!("(tokens: {least}{} in, {} out)", u.input, u.output); + } if a.transcript.iter().any(|e| matches!(e, Entry::Error(_))) { return Err("the assistant couldn't finish".into()); } diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 968ee83d91..79fe191ad7 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -166,6 +166,9 @@ pub struct Agent { allowed: Vec, /// The agents on this computer the model may delegate to ([`acp`]). harnesses: Vec<&'static acp::AgentSpec>, + /// The tokens this message's requests took, subagents' included; agent threads on this + /// computer bill their own ([`Agent::usage`]). + usage: provider::Usage, /// Model requests left for this message (a subagent shares its parent's budget). max_steps: u32, /// Agent threads on this computer, working or waiting for a follow-up. @@ -248,6 +251,7 @@ impl Agent { threads_started: 0, delegations: Vec::new(), reports: Vec::new(), + usage: provider::Usage::default(), max_steps: MAX_STEPS, } } @@ -333,7 +337,11 @@ impl Agent { } waiting.push_str(&message) } - _ => a.turns.push(Turn::User(message, Vec::new())), + _ => { + a.turns.push(Turn::User(message, Vec::new())); + // A turn of its own counts afresh; joining a message still waiting adds to it. + a.usage = provider::Usage::default(); + } } a.steps = 0; a.retries = 0; @@ -465,6 +473,16 @@ impl Agent { Scope::assistant(self.conversation, self.live.clone()) } + /// The tokens the last message's requests took so far, as the provider counts them. `None` when + /// it doesn't say. + pub fn usage(&self) -> Option { + let mut usage = self.usage; + if let Some(child) = &self.child { + usage.add(child.usage); + } + (usage.input > 0 || usage.output > 0).then_some(usage) + } + /// Changes in the generation tell a caller its response is stale. pub fn generation(&self) -> u64 { self.generation @@ -477,6 +495,7 @@ impl Agent { self.turns.clear(); self.transcript.clear(); self.state = State::Idle; + self.usage = provider::Usage::default(); self.steps = 0; self.last_context.clear(); self.always.clear(); @@ -575,7 +594,11 @@ impl Agent { ))); } } - _ => self.turns.push(Turn::User(message, pictures)), + _ => { + self.turns.push(Turn::User(message, pictures)); + // A turn of its own counts afresh; joining one still waiting adds to its count. + self.usage = provider::Usage::default(); + } } self.steps = 0; self.retries = 0; @@ -812,6 +835,10 @@ impl Agent { } self.preview = None; let parsed = resp.as_ref().map_err(Clone::clone).and_then(|r| provider::parse_reply(self.config.api(), r)); + // A request that failed may still have been charged for, without saying how much. + if parsed.is_err() { + self.usage.partial = true; + } if self.config.provider == "openrouter" && matches!(&parsed, Err(e) if e.status == Some(404) && { let detail = e.detail.to_ascii_lowercase(); @@ -848,6 +875,8 @@ impl Agent { } self.retries = 0; if let Ok(reply) = &parsed { + // A request that doesn't say is noted, so the total isn't taken for the whole. + self.usage.add(reply.usage.unwrap_or(provider::Usage { partial: true, ..Default::default() })); self.transcript.extend(reply.notes.iter().cloned().map(Entry::Note)); } if let State::Compacting { upto, resume } = self.state { @@ -1129,6 +1158,7 @@ impl Agent { let Some(child) = self.child.take() else { return Step::Done }; // Its steps count against this message's budget; its "always" approvals stay. self.steps = self.steps.saturating_add(child.steps); + self.usage.add(child.usage); for key in &child.always { if self.always.contains(key) { continue; @@ -1241,10 +1271,16 @@ impl Agent { if !self.busy() { return; } + // A request stopped on its way may have been charged for without saying. + if matches!(self.state, State::Waiting | State::Compacting { .. }) { + self.usage.partial = true; + } if let Some(child) = self.child.as_mut() { child.stop(); self.show_child(); - self.child = None; + if let Some(child) = self.child.take() { + self.usage.add(child.usage); + } } self.halt(Entry::Note(Note::new("Stopped.")), "Stopped by the user.", "Stopped by the user."); } @@ -1294,7 +1330,9 @@ impl Agent { fn halt(&mut self, why: Entry, queued: &str, interrupted: &str) { self.live.0.store(false, Ordering::SeqCst); self.pending_policy = None; - self.child = None; + if let Some(child) = self.child.take() { + self.usage.add(child.usage); + } self.retrying_summary = None; self.retries = 0; self.preview = None; diff --git a/crates/assistant/src/provider.rs b/crates/assistant/src/provider.rs index 526545b966..e520565e55 100644 --- a/crates/assistant/src/provider.rs +++ b/crates/assistant/src/provider.rs @@ -232,12 +232,19 @@ pub struct Config { /// Whether the catalog offers reasoning for the selected model (`Some(false)` also turns it off /// for a Chat Completions model that refused it alongside tools: see [`refuses_reasoning_with_tools`]). pub reasoning: Option, + /// How hard the model thinks, as the ChatGPT catalog names it; empty for [`DEFAULT_EFFORT`]. + pub effort: String, + /// The efforts the catalog offers for the selected model; empty when it doesn't say. + pub efforts: Vec, /// OpenRouter routing excludes endpoints that collect request data by default. pub openrouter_private: bool, /// Requested tool output token estimate (default 10,000); the 24,000-token hard limit still applies. pub tool_output_token_limit: usize, } +/// The reasoning effort on a ChatGPT plan unless another is chosen. +pub const DEFAULT_EFFORT: &str = "medium"; + impl std::fmt::Debug for Config { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Config").field("provider", &self.provider).field("model", &self.model).finish_non_exhaustive() @@ -245,6 +252,18 @@ impl std::fmt::Debug for Config { } impl Config { + /// The effort requests ask for: the one chosen where the model takes it, else the default, else + /// the first it takes. + pub fn effort_sent(&self) -> &str { + // A catalog that doesn't say takes the default alone: another might be refused. + let takes = |e: &str| (self.efforts.is_empty() && e == DEFAULT_EFFORT) || self.efforts.iter().any(|x| x == e); + match self.effort.trim() { + chosen if takes(chosen) => chosen, + _ if takes(DEFAULT_EFFORT) => DEFAULT_EFFORT, + _ => self.efforts.first().map_or(DEFAULT_EFFORT, String::as_str), + } + } + /// The preset's defaults, with a key and base URL from the environment where set. A sign-in /// provider's account is not read here: its tokens are in the system keychain, which may block /// (`chatgpt::load_any`, then [`Config::sign_in`]). @@ -266,6 +285,8 @@ impl Config { client_id: String::new(), session: String::new(), reasoning: None, + effort: env("RUSTGIS_ASSISTANT_EFFORT").unwrap_or_default(), + efforts: Vec::new(), openrouter_private: env("RUSTGIS_OPENROUTER_DATA_COLLECTION").as_deref() != Some("allow"), tool_output_token_limit: env("RUSTGIS_ASSISTANT_TOOL_OUTPUT_TOKEN_LIMIT") .and_then(|s| s.parse().ok()) @@ -804,6 +825,48 @@ impl std::fmt::Display for Note { } } +/// The tokens a request took, as the provider counts them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Usage { + /// What was sent, cached or not. + pub input: u64, + /// What came back, reasoning included. + pub output: u64, + /// Some of the requests counted didn't say what they took: the counts are less than it was. + pub partial: bool, +} + +impl Usage { + /// The counts in a reply, in whichever API's form it has them. `None` when it has none. + fn of(reply: &Value) -> Option { + let sum = |v: &Value, keys: &[&str]| { + let found: Vec = keys.iter().filter_map(|k| v.get(k).and_then(Value::as_u64)).collect(); + found.iter().copied().reduce(u64::saturating_add) + }; + let (input, output) = match (reply.get("usage"), reply.get("usageMetadata")) { + (Some(u), _) if u.is_object() => ( + // Anthropic's input_tokens leaves out what the cache read and wrote. + sum(u, &["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "prompt_tokens"]), + sum(u, &["output_tokens", "completion_tokens"]), + ), + (_, Some(u)) => (sum(u, &["promptTokenCount"]), sum(u, &["candidatesTokenCount", "thoughtsTokenCount"])), + _ => return None, + }; + // One count without the other is a total that is short, not a zero. + (input.is_some() || output.is_some()).then(|| Usage { + input: input.unwrap_or(0), + output: output.unwrap_or(0), + partial: input.is_none() || output.is_none(), + }) + } + + pub(crate) fn add(&mut self, more: Usage) { + self.input = self.input.saturating_add(more.input); + self.output = self.output.saturating_add(more.output); + self.partial |= more.partial; + } +} + /// A reply read from the provider. #[derive(Clone, Debug)] pub struct Reply { @@ -816,6 +879,8 @@ pub struct Reply { pub cut: Option, /// A failed terminal response accompanying partial text. pub failure: Option, + /// The tokens it took, if the provider says. + pub usage: Option, } /// Replies may be long (tables, explanations) but are never documents. @@ -861,7 +926,8 @@ fn parse_reply_inner(api: Api, resp: &HttpResponse) -> Result { e.request_id = resp.request_id().map(str::to_string); return Err(e); } - parse(&v).map_err(Error::from) + let usage = Usage::of(&v); + parse(&v).map(|r| Reply { usage, ..r }).map_err(Error::from) } // --------------------------------------------------------------------------------------------- @@ -927,6 +993,8 @@ fn stream_ended(api: Api, text: &str, events: &[Value]) -> bool { fn openai_assembled(events: &[Value]) -> Value { let (mut content, mut reasoning, mut finish) = (Value::Null, String::new(), Value::Null); let mut calls: Vec<(String, String, String)> = Vec::new(); + // The last chunk's, which has no choices. + let usage = events.iter().rev().find_map(|e| e.get("usage").filter(|u| u.is_object())); for e in events { for choice in e.get("choices").and_then(Value::as_array).into_iter().flatten() { let delta = choice.get("delta").unwrap_or(&Value::Null); @@ -993,7 +1061,7 @@ fn openai_assembled(events: &[Value]) -> Value { if !reasoning.is_empty() { message["reasoning_content"] = json!(reasoning); } - json!({"choices": [{"finish_reason": finish, "message": message}]}) + json!({"choices": [{"finish_reason": finish, "message": message}], "usage": usage}) } /// Anthropic events: content blocks started, extended by deltas (text, tool input JSON, @@ -1041,6 +1109,13 @@ fn anthropic_assembled(events: &[Value]) -> Value { for (k, v) in e.get("delta").and_then(Value::as_object).into_iter().flatten() { message[k] = v.clone(); } + // The counts at the end replace those of the start, kind by kind. + for (k, v) in e.get("usage").and_then(Value::as_object).into_iter().flatten().filter(|(_, v)| v.is_u64()) { + if !message["usage"].is_object() { + message["usage"] = json!({}); + } + message["usage"][k] = v.clone(); + } } _ => {} } @@ -1069,6 +1144,7 @@ fn gemini_assembled(events: &[Value]) -> Value { let mut parts: Vec = Vec::new(); let mut finish = Value::Null; let mut feedback = Value::Null; + let usage = events.iter().rev().find_map(|e| e.get("usageMetadata")); for e in events { if let Some(f) = e.get("promptFeedback") { feedback = f.clone(); @@ -1082,7 +1158,7 @@ fn gemini_assembled(events: &[Value]) -> Value { if parts.is_empty() && finish.is_null() { return json!({"promptFeedback": feedback}); } - json!({"candidates": [{"content": {"role": "model", "parts": parts}, "finishReason": finish}]}) + json!({"candidates": [{"content": {"role": "model", "parts": parts}, "finishReason": finish}], "usageMetadata": usage}) } /// A streamed reply's text so far, for showing while it arrives (what runs is read from the @@ -1236,6 +1312,11 @@ fn openai_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDef]) .map(|t| json!({"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.schema}})) .collect(); let mut body = json!({"model": cfg.model.trim(), "messages": messages, "stream": true}); + // OpenAI counts a stream's tokens only when asked. Other servers aren't: some refuse fields + // they don't know. + if cfg.provider == "openai" && preset("openai").is_some_and(|p| cfg.base() == p.base_url) { + body["stream_options"] = json!({"include_usage": true}); + } if cfg.provider == "openrouter" && cfg.openrouter_private { body["provider"] = json!({"data_collection": "deny"}); } @@ -1417,7 +1498,7 @@ fn openai_reply(v: &Value) -> Result { if let Some(o) = native.as_object_mut() { o.retain(|k, _| matches!(k.as_str(), "role" | "content" | "tool_calls" | "reasoning_content")); } - Ok(Reply { text, calls, native, notes, cut, failure: None }) + Ok(Reply { text, calls, native, notes, cut, failure: None, usage: None }) } // --------------------------------------------------------------------------------------------- @@ -1478,7 +1559,7 @@ fn responses_request(cfg: &Config, system: &str, turns: &[Turn], tools: &[ToolDe }); // Older catalogs omit the capability; keep the existing behavior in that case. if cfg.reasoning != Some(false) { - body["reasoning"] = json!({"effort": "medium"}); + body["reasoning"] = json!({"effort": cfg.effort_sent()}); body["include"] = json!(["reasoning.encrypted_content"]); } if !functions.is_empty() { @@ -1638,7 +1719,7 @@ fn responses_reply(resp: &HttpResponse) -> Result { }) .collect(); let failure = (!completed && last.get("error").is_some_and(Value::is_object)).then(|| Error::response(&last, resp)); - Ok(Reply { text, calls, native: Value::Array(native), notes: Vec::new(), cut, failure }) + Ok(Reply { text, calls, native: Value::Array(native), notes: Vec::new(), cut, failure, usage: Usage::of(&last) }) } // --------------------------------------------------------------------------------------------- @@ -1765,7 +1846,7 @@ fn anthropic_reply(v: &Value) -> Result { if v.get("stop_reason").and_then(Value::as_str) == Some("refusal") { calls.clear(); } - Ok(Reply { text, calls, native: Value::Array(content.clone()), notes: Vec::new(), cut, failure: None }) + Ok(Reply { text, calls, native: Value::Array(content.clone()), notes: Vec::new(), cut, failure: None, usage: None }) } // --------------------------------------------------------------------------------------------- @@ -1905,7 +1986,7 @@ fn gemini_reply(v: &Value) -> Result { if native.get("role").is_none() { native["role"] = json!("model"); } - Ok(Reply { text, calls, native, notes: Vec::new(), cut, failure: None }) + Ok(Reply { text, calls, native, notes: Vec::new(), cut, failure: None, usage: None }) } /// `v` if it is an object, else an empty one (providers require objects for tool input). @@ -2006,6 +2087,8 @@ pub struct Model { pub name: String, /// Reasoning support, or unknown for older catalogs. pub reasoning: Option, + /// The reasoning efforts it takes; empty for catalogs that don't say. + pub efforts: Vec, } /// Reads the visible ChatGPT catalog, in server order. @@ -2025,7 +2108,15 @@ pub fn parse_catalog(resp: &HttpResponse) -> Result, Error> { .get("supports_reasoning") .and_then(Value::as_bool) .or_else(|| m.get("supported_reasoning_levels").and_then(Value::as_array).map(|a| !a.is_empty())); - Some(Model { id: id.into(), name: m.get("display_name").and_then(Value::as_str).unwrap_or(id).into(), reasoning }) + // Each a name, or an object with one. + let efforts = m.get("supported_reasoning_levels").and_then(Value::as_array).into_iter().flatten(); + let efforts = efforts + .filter_map(|l| l.as_str().or_else(|| l.get("effort").and_then(Value::as_str))) + .filter(|l| !l.is_empty() && l.len() <= 32) + .take(16) + .map(str::to_string) + .collect(); + Some(Model { id: id.into(), name: m.get("display_name").and_then(Value::as_str).unwrap_or(id).into(), reasoning, efforts }) }) .take(2000) .collect()) @@ -2035,6 +2126,7 @@ pub fn parse_catalog(resp: &HttpResponse) -> Result, Error> { pub fn use_catalog(cfg: &mut Config, models: &[Model], explicit: bool) { let selected = models.iter().find(|m| m.id == cfg.model).or_else(|| if explicit { None } else { models.first() }); cfg.reasoning = selected.and_then(|m| m.reasoning); + cfg.efforts = selected.map(|m| m.efforts.clone()).unwrap_or_default(); if let Some(model) = selected { cfg.model = model.id.clone(); } diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index cdc7803ba7..2fade6d487 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -54,6 +54,8 @@ fn cfg(provider: &str) -> Config { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: crate::tools::DEFAULT_OUTPUT_TOKENS, } @@ -2530,6 +2532,124 @@ fn incomplete_responses_never_execute_or_replay_calls() { } } +#[test] +fn the_effort_chosen_is_sent_where_the_model_takes_it() { + let response = HttpResponse { + status: 200, + headers: vec![], + body: json!({"models": [ + {"slug":"both", "visibility":"list", "supported_reasoning_levels":[{"effort":"low"}, {"effort":"medium"}, "high", {"x":1}, 3]}, + {"slug":"high-only", "visibility":"list", "supported_reasoning_levels":["high"]}, + {"slug":"unsaid", "visibility":"list"} + ]}) + .to_string() + .into_bytes(), + }; + let models = parse_catalog(&response).unwrap(); + assert_eq!(models[0].efforts, ["low", "medium", "high"]); + let sent = |model: &str, effort: &str| { + let mut cfg = Config { model: model.into(), effort: effort.into(), ..chatgpt_cfg() }; + use_catalog(&mut cfg, &models, true); + body(&chat_request(&cfg, "hello", &[], &[]))["reasoning"]["effort"].as_str().unwrap().to_string() + }; + assert_eq!([sent("both", ""), sent("both", "high"), sent("both", "gone")], ["medium", "high", "medium"]); + assert_eq!([sent("high-only", ""), sent("high-only", "low")], ["high", "high"]); + assert_eq!([sent("unsaid", ""), sent("unsaid", "typo")], ["medium", "medium"]); +} + +#[test] +fn every_api_says_its_tokens_streamed_or_not() { + let http = |text: String| HttpResponse { status: 200, headers: vec![], body: text.into_bytes() }; + let stream = |events: &[Value]| http(events.iter().map(|e| format!("data: {e}\n\n")).collect()); + let usage = |api, r: HttpResponse| parse_reply(api, &r).unwrap().usage; + let want = Some(Usage { input: 120, output: 30, partial: false }); + + let counts = json!({"prompt_tokens": 120, "completion_tokens": 30, "total_tokens": 150}); + let mut plain = say("hi"); + assert_eq!(usage(Api::OpenAi, http(plain.to_string())), None); + plain["usage"] = counts.clone(); + assert_eq!(usage(Api::OpenAi, http(plain.to_string())), want); + let chunk = json!({"choices": [{"delta": {"content": "hi"}, "finish_reason": "stop"}], "usage": null}); + assert_eq!(usage(Api::OpenAi, stream(&[chunk.clone(), json!({"choices": [], "usage": counts})])), want); + assert_eq!(usage(Api::OpenAi, stream(&[chunk])), None); + + let start = json!({"type": "message_start", "message": {"usage": {"input_tokens": 20, "cache_read_input_tokens": 90, "cache_creation_input_tokens": 10, "output_tokens": 1}}}); + let block = json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": "hi"}}); + let end = json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 30}}); + assert_eq!(usage(Api::Anthropic, stream(&[start, block, end, json!({"type": "message_stop"})])), want); + + let gemini = json!({"candidates": [{"content": {"parts": [{"text": "hi"}]}, "finishReason": "STOP"}], + "usageMetadata": {"promptTokenCount": 120, "candidatesTokenCount": 10, "thoughtsTokenCount": 20}}); + assert_eq!(usage(Api::Gemini, stream(&[gemini])), want); + + let done = json!({"type": "response.completed", "response": {"status": "completed", "output": [], "usage": {"input_tokens": 120, "output_tokens": 30}}}); + assert_eq!(usage(Api::Responses, stream(&[done])), want); + + // One count without the other is short, not zero. + let mut half = say("hi"); + half["usage"] = json!({"prompt_tokens": 120}); + assert_eq!(usage(Api::OpenAi, http(half.to_string())), Some(Usage { input: 120, output: 0, partial: true })); + // Nonsense counts are none. + for bad in [json!(3), json!([]), json!({"prompt_tokens": -1, "completion_tokens": "many"})] { + plain["usage"] = bad; + assert_eq!(usage(Api::OpenAi, http(plain.to_string())), None); + } + // Only OpenAI itself is asked for them. + let asks = |c: &Config| body(&chat_request(c, "s", &[], &[])).get("stream_options").is_some(); + let elsewhere = Config { base_url: "https://proxy.example/v1".into(), ..cfg("openai") }; + assert!(asks(&cfg("openai")) && !asks(&elsewhere) && !asks(&cfg("mistral")) && !asks(&cfg("custom"))); +} + +#[test] +fn a_messages_tokens_add_up_with_its_subagents() { + let mut s = sample(); + let mut a = Agent::new(cfg("openai"), &s); + let with = |mut reply: Value, input: u64| { + reply["usage"] = json!({"prompt_tokens": input, "completion_tokens": 1}); + ok(reply) + }; + a.ask("look", &s); + assert_eq!(a.usage(), None); + a.receive(a.generation(), with(call("1", "delegate", json!({"task": "look"})), 10), &mut s); + a.receive(a.generation(), with(call("2", "list_layers", json!({})), 200), &mut s); + assert_eq!(a.usage(), Some(Usage { input: 210, output: 2, partial: false }), "a subagent still at work counts"); + a.receive(a.generation(), with(say("seen"), 300), &mut s); + a.receive(a.generation(), with(say("done"), 4000), &mut s); + assert_eq!(a.usage(), Some(Usage { input: 4510, output: 4, partial: false })); + a.ask("again", &s); + assert_eq!(a.usage(), None, "counted by message"); + // A request that doesn't say makes the total a lower bound. + a.receive(a.generation(), with(call("q", "list_layers", json!({})), 50), &mut s); + a.receive(a.generation(), ok(say("done")), &mut s); + assert_eq!(a.usage(), Some(Usage { input: 50, output: 1, partial: true })); + a.ask("again", &s); + // A message joining the turn a compaction left adds to the summary's count. + a.stop(); + assert!(matches!(a.compact(), Step::Send(_))); + a.receive(a.generation(), with(say("Summary: looked at the layers."), 40), &mut s); + a.ask("go on", &s); + assert!(a.usage().is_some_and(|u| u.input == 40), "{:?}", a.usage()); + a.clear(); + // A request that fails makes the total a lower bound too. + a.ask("again", &s); + a.receive(a.generation(), with(call("f", "list_layers", json!({})), 70), &mut s); + a.receive(a.generation(), Err("the connection closed".into()), &mut s); + assert!(a.usage().is_some_and(|u| u.partial && u.input == 70)); + a.stop(); + a.ask("once more", &s); + // A request stopped on its way makes it a lower bound. + a.receive(a.generation(), with(call("g", "list_layers", json!({})), 30), &mut s); + a.stop(); + assert!(a.usage().is_some_and(|u| u.partial && u.input == 30)); + a.ask("and again", &s); + // A stop keeps what the subagent had taken. + a.receive(a.generation(), with(call("3", "delegate", json!({"task": "look"})), 10), &mut s); + a.receive(a.generation(), with(call("4", "list_layers", json!({})), 200), &mut s); + a.stop(); + // Its request still out when stopped, the total is a lower bound. + assert_eq!(a.usage(), Some(Usage { input: 210, output: 2, partial: true })); +} + #[test] fn catalog_defaults_names_and_reasoning_capabilities() { let response = HttpResponse { diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 026a51b973..ded53b0388 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -108,6 +108,8 @@ pub struct AssistantState { pub(crate) retry: Option<(u64, web_time::Instant)>, /// The user lets the assistant hand tasks to local agents (Claude Code, Codex). pub(crate) local_agents: bool, + /// The tokens a message took are left out of the conversation (shown unless the user says). + pub(crate) hide_tokens: bool, /// Agent threads on this computer: their processes, windows and requests (desktop). #[cfg(not(target_arch = "wasm32"))] pub(crate) threads: crate::agentthreads::Threads, @@ -143,6 +145,28 @@ impl AssistantState { self.agent.as_ref().map_or(&[], |a| a.transcript.as_slice()) } + /// A line of the tokens the last message took so far, "at least" when some of its requests + /// didn't say; `None` when none did, or when the user turned the line off. + pub fn usage_line(&self) -> Option { + if self.hide_tokens { + return None; + } + let usage = self.agent.as_ref().and_then(Agent::usage)?; + // Digits in threes, apart by a space, which reads the same in every language. + let count = |n: u64| { + let digits = n.to_string(); + let threes: Vec = digits.as_bytes().rchunks(3).rev().map(|c| String::from_utf8_lossy(c).into_owned()).collect(); + threes.join(" ") + }; + let counts = [("input", count(usage.input)), ("output", count(usage.output))]; + let counts = counts.each_ref().map(|(k, v)| (*k, v.as_str())); + Some(if usage.partial { + crate::i18n::fmt("Tokens for this message: at least {input} in, {output} out (some requests didn't say)", &counts) + } else { + crate::i18n::fmt("Tokens for this message: {input} in, {output} out", &counts) + }) + } + /// The text so far of a reply still streaming in. pub fn preview(&self) -> Option<&str> { self.agent.as_ref().and_then(Agent::preview) @@ -251,6 +275,20 @@ pub(crate) fn pref(app: &RustGisApp, key: &str) -> Option { app.services.load_pref.as_ref().and_then(|l| l(key)).filter(|v| !v.is_empty()) } +/// The preference that hides the tokens a message took ("off"), shown otherwise. +const TOKENS_PREF: &str = "assistant_show_tokens"; + +/// Shows or hides the tokens each message took, and remembers it. +pub fn show_tokens(app: &mut RustGisApp, show: bool) { + app.assistant.hide_tokens = !show; + save_pref(app, TOKENS_PREF, if show { "on" } else { "off" }); +} + +/// Whether the tokens each message took are shown. +pub fn showing_tokens(app: &RustGisApp) -> bool { + !app.assistant.hide_tokens +} + /// Saves a preference through the platform hook. pub(crate) fn save_pref(app: &RustGisApp, key: &str, value: &str) { if let Some(s) = &app.services.save_pref { @@ -270,6 +308,9 @@ fn load_config(app: &mut RustGisApp, provider: &str, ctx: &egui::Context) -> Con if provider == "openrouter" { c.openrouter_private = pref(app, provider::OPENROUTER_PRIVATE_PREF).as_deref() != Some("off"); } + if let Some(effort) = pref(app, &format!("assistant_effort_{provider}")).filter(|_| c.login()) { + c.effort = effort; + } if !c.login() { let legacy = pref(app, &format!("assistant_key_{provider}")); #[cfg(not(target_arch = "wasm32"))] @@ -328,6 +369,7 @@ pub(crate) fn ensure_loaded(app: &mut RustGisApp, ctx: &egui::Context) { } let mut agent = Agent::new(cfg, &app.session); app.assistant.local_agents = pref(app, "assistant_local_agents").as_deref() == Some("on"); + app.assistant.hide_tokens = pref(app, TOKENS_PREF).as_deref() == Some("off"); #[cfg(not(target_arch = "wasm32"))] { app.assistant.agents_auto = pref(app, "assistant_agents_auto").as_deref() == Some("on"); @@ -513,6 +555,11 @@ pub(crate) fn save_config(app: &mut RustGisApp, c: &Config, ctx: &egui::Context) // A key from the environment stays there; a sign-in's tokens live in their own file. let from_env = Config::from_env(&c.provider).key; if c.login() { + let name = format!("assistant_effort_{}", c.provider); + // The environment's choice stays there, unless another was made here. + if c.effort != Config::from_env(&c.provider).effort || pref(app, &name).is_some() { + save_pref(app, &name, &c.effort); + } return; } let pref_key = format!("assistant_key_{}", c.provider); diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 2c13221779..dfde4c4cfb 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -122,6 +122,14 @@ fn settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { { ui.label(RichText::new(tl!(why)).small().color(t.amber)); } + let mut tokens = assistant::showing_tokens(app); + if ui + .checkbox(&mut tokens, tl!("Show the tokens each message uses")) + .on_hover_text(tl!("As the provider counts them, under the last reply. Some servers don't say.")) + .changed() + { + assistant::show_tokens(app, tokens); + } #[cfg(not(target_arch = "wasm32"))] local_agents_setting(app, ui, t); #[cfg(not(target_arch = "wasm32"))] @@ -219,6 +227,22 @@ fn provider_settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, cfg: &mut Co }); }); ui.end_row(); + if cfg.login() && !signed_out && cfg.reasoning != Some(false) && !cfg.efforts.is_empty() { + let effort_label = ui.label(tl!("Effort")); + egui::ComboBox::from_id_salt("assistant_effort") + .selected_text(cfg.effort_sent().to_string()) + .show_ui(ui, |ui| { + for effort in cfg.efforts.clone() { + if ui.selectable_label(cfg.effort_sent() == effort, &effort).clicked() { + cfg.effort = effort; + } + } + }) + .response + .labelled_by(effort_label.id) + .on_hover_text(tl!("How much the model thinks before it answers. More is slower and uses more of your plan.")); + ui.end_row(); + } let preset = provider::preset(&cfg.provider); if !cfg.login() { let address_label = ui.label(tl!("Address")); @@ -829,6 +853,11 @@ fn transcript(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context } } } + if !app.assistant.busy() + && let Some(line) = app.assistant.usage_line() + { + ui.label(RichText::new(line).small().color(t.text_dim)); + } if app.assistant.waiting() { // The reply so far, as it streams in. if let Some(text) = app.assistant.preview() { @@ -1321,6 +1350,38 @@ pub(crate) mod tests { ) } + /// The tokens a message took show under it, until the setting turns them off, which is kept. + #[test] + fn the_tokens_line_follows_its_setting() { + use egui_kittest::kittest::Queryable; + use std::sync::{Arc, Mutex}; + let mut app = plan_app(); + let saved = Arc::new(Mutex::new(Vec::new())); + let keep = saved.clone(); + app.services.save_pref = Some(Box::new(move |k, v| keep.lock().unwrap().push((k.to_string(), v.to_string())))); + let mut agent = Agent::new(Config { model: "m".into(), ..Config::from_env("custom") }, &app.session); + agent.ask("hi", &app.session); + let body = serde_json::json!({"choices": [{"message": {"role": "assistant", "content": "Hello."}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1234, "completion_tokens": 5}}); + let body = body.to_string().into_bytes(); + agent.receive(agent.generation(), Ok(HttpResponse { status: 200, body, headers: vec![] }), &mut app.session); + app.assistant.agent = Some(agent); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 860.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h.get_by_label("Tokens for this message: 1 234 in, 5 out"); + h.get_by_label("Show the tokens each message uses").click(); + h.run_steps(4); + assert!(h.query_by_label("Tokens for this message: 1 234 in, 5 out").is_none()); + assert!(saved.lock().unwrap().contains(&("assistant_show_tokens".into(), "off".into()))); + } + /// The actual Remember checkbox goes through the deferred save path and deletes the stored key. #[cfg(not(target_arch = "wasm32"))] #[test] @@ -1769,6 +1830,8 @@ pub(crate) mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; @@ -2253,6 +2316,8 @@ pub(crate) mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; @@ -2275,6 +2340,8 @@ pub(crate) mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; diff --git a/crates/ui-egui/src/assistantpictures.rs b/crates/ui-egui/src/assistantpictures.rs index ad8f1387e9..6dfd4c1713 100644 --- a/crates/ui-egui/src/assistantpictures.rs +++ b/crates/ui-egui/src/assistantpictures.rs @@ -523,6 +523,8 @@ mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; diff --git a/crates/ui-egui/src/localagents.rs b/crates/ui-egui/src/localagents.rs index 54e4508886..570f6905d2 100644 --- a/crates/ui-egui/src/localagents.rs +++ b/crates/ui-egui/src/localagents.rs @@ -683,6 +683,8 @@ mod tests { client_id: String::new(), session: String::new(), reasoning: None, + effort: String::new(), + efforts: Vec::new(), openrouter_private: true, tool_output_token_limit: rustgis_assistant::tools::DEFAULT_OUTPUT_TOKENS, }; diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index e3fbf1d6a7..4ce3b18fd3 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -446,6 +446,11 @@ fn messages(app: &RustGisApp, ui: &mut Ui, t: &Tokens) { } } } + if !app.assistant.busy() + && let Some(line) = app.assistant.usage_line() + { + ui.label(RichText::new(line).size(13.0).color(t.text_dim)); + } if app.assistant.waiting() { match app.assistant.preview() { Some(text) => { @@ -667,6 +672,10 @@ fn settings_form(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat } } } + let tokens = assistant::showing_tokens(app); + if toggle_chip(ui, t, tl!("Show the tokens each message uses"), ui.available_width(), tokens) { + assistant::show_tokens(app, !tokens); + } if let Some(why) = cfg.missing() { ui.label(RichText::new(tl!(why)).size(14.0).color(t.amber)); } else if action(ui, t, if started { tl!("Done") } else { tl!("Start") }, ui.available_width(), true, true) { diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index d9f0166b7b..f794894b4b 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -141,6 +141,20 @@ field changes the endpoint for providers other than ChatGPT; use the OpenAI-comp path (usually `/v1`) for local servers. Models that call tools well give the best results; small local models may stop early or skip steps. +### Tokens and effort + +After each message, the pane shows the tokens its requests took, subagents' included (agent +threads on this computer bill their own and aren't counted), as the +provider counts them. Tokens in are counted for every request, so a long run counts the +conversation many times, though providers usually charge less for what they had cached. Nothing +is shown for a server that doesn't report them, and "at least" when some of a message's requests +didn't. **Show the tokens each message uses** in the settings turns the line off. + +With a ChatGPT sign-in, **Effort** sets how much the model thinks before it answers, where the +model offers a choice: `medium` unless you choose, or the model's first level when it has no +`medium`. `RUSTGIS_ASSISTANT_EFFORT` sets it for the app and the command line until one is chosen +in the settings; a level the model doesn't list isn't sent, and the command line says so. + ### OpenRouter private routing **Private routing** is on by default for OpenRouter. Every chat request, including summaries