Thinking levels: Tab cycles off/low/medium/high, /effort
This commit is contained in:
1 parent
2f1ce2c072
commit
ab2af421a4
9 files changed
+180
-16
No files matched your search
@@ -120,6 +120,18 @@ pub fn body(req: &Request) -> Value {
|
|||||||
if !tools.is_empty() {
|
if !tools.is_empty() {
|
||||||
b["tools"] = tools.into();
|
b["tools"] = tools.into();
|
||||||
}
|
}
|
||||||
|
// ponytail: fixed token budgets; newer models may prefer adaptive thinking, add when needed
|
||||||
|
let budget = match req.effort {
|
||||||
|
crate::Effort::Off => 0,
|
||||||
|
crate::Effort::Low => 4_000,
|
||||||
|
crate::Effort::Medium => 10_000,
|
||||||
|
crate::Effort::High => 24_000,
|
||||||
|
};
|
||||||
|
if budget > 0 {
|
||||||
|
b["thinking"] = json!({"type": "enabled", "budget_tokens": budget});
|
||||||
|
// the budget counts against max_tokens, which must leave room for the reply
|
||||||
|
b["max_tokens"] = req.max_tokens.max(budget + 4_096).into();
|
||||||
|
}
|
||||||
b
|
b
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,6 +389,16 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::ToolSpec;
|
use crate::ToolSpec;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effort_sets_thinking_budget() {
|
||||||
|
let mut r = req();
|
||||||
|
assert!(body(&r).get("thinking").is_none());
|
||||||
|
r.effort = crate::Effort::High;
|
||||||
|
let b = body(&r);
|
||||||
|
assert_eq!(b["thinking"]["budget_tokens"], 24_000);
|
||||||
|
assert!(b["max_tokens"].as_u64().unwrap() > 24_000);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn quota_and_models() {
|
fn quota_and_models() {
|
||||||
let mut h = reqwest::header::HeaderMap::new();
|
let mut h = reqwest::header::HeaderMap::new();
|
||||||
@@ -427,6 +449,7 @@ mod tests {
|
|||||||
input_schema: json!({"type": "object"}),
|
input_schema: json!({"type": "object"}),
|
||||||
}],
|
}],
|
||||||
max_tokens: 1024,
|
max_tokens: 1024,
|
||||||
|
effort: crate::Effort::Off,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ pub struct Codex {
|
|||||||
auth: Auth,
|
auth: Auth,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
http: reqwest::Client,
|
http: reqwest::Client,
|
||||||
/// "none" | "minimal" | "low" | "medium" | "high"
|
|
||||||
pub reasoning_effort: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Codex {
|
impl Codex {
|
||||||
@@ -22,7 +20,6 @@ impl Codex {
|
|||||||
auth,
|
auth,
|
||||||
base_url: "https://chatgpt.com/backend-api/codex".into(),
|
base_url: "https://chatgpt.com/backend-api/codex".into(),
|
||||||
http: reqwest::Client::new(),
|
http: reqwest::Client::new(),
|
||||||
reasoning_effort: Some("medium".into()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn login_default() -> Result<Self> {
|
pub fn login_default() -> Result<Self> {
|
||||||
@@ -42,7 +39,7 @@ fn split_id(id: &str) -> (&str, Option<&str>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn body(req: &Request, effort: Option<&str>) -> Value {
|
pub fn body(req: &Request) -> Value {
|
||||||
let mut input = vec![];
|
let mut input = vec![];
|
||||||
for m in &req.messages {
|
for m in &req.messages {
|
||||||
for b in &m.content {
|
for b in &m.content {
|
||||||
@@ -109,9 +106,12 @@ pub fn body(req: &Request, effort: Option<&str>) -> Value {
|
|||||||
"text": {"verbosity": "low"},
|
"text": {"verbosity": "low"},
|
||||||
"include": ["reasoning.encrypted_content"],
|
"include": ["reasoning.encrypted_content"],
|
||||||
});
|
});
|
||||||
if let Some(e) = effort {
|
// Off has no Codex equivalent (see Effort::levels); send the lowest level instead
|
||||||
b["reasoning"] = json!({"effort": e, "summary": "auto"});
|
let e = match req.effort {
|
||||||
}
|
crate::Effort::Off | crate::Effort::Low => "low",
|
||||||
|
e => e.name(),
|
||||||
|
};
|
||||||
|
b["reasoning"] = json!({"effort": e, "summary": "auto"});
|
||||||
b
|
b
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,7 +368,7 @@ impl Provider for Codex {
|
|||||||
.header("OpenAI-Beta", "responses=experimental")
|
.header("OpenAI-Beta", "responses=experimental")
|
||||||
.header("accept", "text/event-stream")
|
.header("accept", "text/event-stream")
|
||||||
.header("user-agent", concat!("hx/", env!("CARGO_PKG_VERSION")))
|
.header("user-agent", concat!("hx/", env!("CARGO_PKG_VERSION")))
|
||||||
.json(&body(&req, self.reasoning_effort.as_deref()))
|
.json(&body(&req))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Error::Http(e.to_string()))?;
|
.map_err(|e| Error::Http(e.to_string()))?;
|
||||||
@@ -528,8 +528,9 @@ mod tests {
|
|||||||
input_schema: json!({"type":"object"}),
|
input_schema: json!({"type":"object"}),
|
||||||
}],
|
}],
|
||||||
max_tokens: 100,
|
max_tokens: 100,
|
||||||
|
effort: crate::Effort::Low,
|
||||||
};
|
};
|
||||||
let b = body(&req, Some("low"));
|
let b = body(&req);
|
||||||
let inp = b["input"].as_array().unwrap();
|
let inp = b["input"].as_array().unwrap();
|
||||||
assert_eq!(inp[0]["content"][0]["type"], "input_text");
|
assert_eq!(inp[0]["content"][0]["type"], "input_text");
|
||||||
assert_eq!(inp[1]["type"], "reasoning");
|
assert_eq!(inp[1]["type"], "reasoning");
|
||||||
|
|||||||
@@ -138,6 +138,99 @@ pub enum StopReason {
|
|||||||
Other,
|
Other,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How hard the model thinks before answering.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Effort {
|
||||||
|
Off,
|
||||||
|
Low,
|
||||||
|
#[default]
|
||||||
|
Medium,
|
||||||
|
High,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Effort {
|
||||||
|
pub const ALL: [Effort; 4] = [Effort::Off, Effort::Low, Effort::Medium, Effort::High];
|
||||||
|
|
||||||
|
/// Start level per provider: Claude thinks only when asked (token cost), Codex always reasons.
|
||||||
|
pub fn default_for(k: auth::Kind) -> Self {
|
||||||
|
match k {
|
||||||
|
auth::Kind::Claude => Effort::Off,
|
||||||
|
auth::Kind::Codex => Effort::Medium,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Levels the provider supports (Codex models can't switch reasoning off).
|
||||||
|
pub fn levels(k: auth::Kind) -> &'static [Effort] {
|
||||||
|
match k {
|
||||||
|
auth::Kind::Claude => &Self::ALL,
|
||||||
|
auth::Kind::Codex => &Self::ALL[1..],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Next level in `levels(k)`, wrapping; a level the provider lacks maps to its first.
|
||||||
|
pub fn next(self, k: auth::Kind) -> Self {
|
||||||
|
let l = Self::levels(k);
|
||||||
|
l.iter()
|
||||||
|
.position(|&e| e == self)
|
||||||
|
.map_or(l[0], |i| l[(i + 1) % l.len()])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Effort::Off => "off",
|
||||||
|
Effort::Low => "low",
|
||||||
|
Effort::Medium => "medium",
|
||||||
|
Effort::High => "high",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod effort_tests {
|
||||||
|
use super::*;
|
||||||
|
use auth::Kind;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cycle_wraps_and_codex_skips_off() {
|
||||||
|
let mut e = Effort::Off;
|
||||||
|
let seen: Vec<_> = (0..5)
|
||||||
|
.map(|_| {
|
||||||
|
e = e.next(Kind::Claude);
|
||||||
|
e
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
seen,
|
||||||
|
[
|
||||||
|
Effort::Low,
|
||||||
|
Effort::Medium,
|
||||||
|
Effort::High,
|
||||||
|
Effort::Off,
|
||||||
|
Effort::Low
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(Effort::High.next(Kind::Codex), Effort::Low);
|
||||||
|
assert_eq!(
|
||||||
|
Effort::Off.next(Kind::Codex),
|
||||||
|
Effort::Low,
|
||||||
|
"unsupported level"
|
||||||
|
);
|
||||||
|
assert_eq!("high".parse::<Effort>(), Ok(Effort::High));
|
||||||
|
assert!("max".parse::<Effort>().is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::str::FromStr for Effort {
|
||||||
|
type Err = String;
|
||||||
|
fn from_str(s: &str) -> std::result::Result<Self, String> {
|
||||||
|
Self::ALL
|
||||||
|
.into_iter()
|
||||||
|
.find(|e| e.name() == s)
|
||||||
|
.ok_or_else(|| format!("unknown level {s:?} (off, low, medium, high)"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
pub model: String,
|
pub model: String,
|
||||||
@@ -145,6 +238,7 @@ pub struct Request {
|
|||||||
pub messages: Vec<Message>,
|
pub messages: Vec<Message>,
|
||||||
pub tools: Vec<ToolSpec>,
|
pub tools: Vec<ToolSpec>,
|
||||||
pub max_tokens: u32,
|
pub max_tokens: u32,
|
||||||
|
pub effort: Effort,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Incremental stream events. Providers must emit `Done` last with the full assembled message.
|
/// Incremental stream events. Providers must emit `Done` last with the full assembled message.
|
||||||
|
|||||||
@@ -544,6 +544,7 @@ async fn main() -> Result<()> {
|
|||||||
cx,
|
cx,
|
||||||
);
|
);
|
||||||
agent.set_model(model);
|
agent.set_model(model);
|
||||||
|
agent.set_effort(hx_ai::Effort::default_for(kind));
|
||||||
agent.set_system(context::system_prompt(
|
agent.set_system(context::system_prompt(
|
||||||
cfg.system_prompt.as_deref(),
|
cfg.system_prompt.as_deref(),
|
||||||
&context::hx_home(),
|
&context::hx_home(),
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ pub struct Agent {
|
|||||||
model: String,
|
model: String,
|
||||||
system: String,
|
system: String,
|
||||||
max_tokens: u32,
|
max_tokens: u32,
|
||||||
|
effort: hx_ai::Effort,
|
||||||
max_turns: u32,
|
max_turns: u32,
|
||||||
usage: Usage,
|
usage: Usage,
|
||||||
session: Session,
|
session: Session,
|
||||||
@@ -71,6 +72,7 @@ impl Agent {
|
|||||||
model: String::new(),
|
model: String::new(),
|
||||||
system: String::new(),
|
system: String::new(),
|
||||||
max_tokens: 16_384,
|
max_tokens: 16_384,
|
||||||
|
effort: hx_ai::Effort::Off,
|
||||||
max_turns: 200,
|
max_turns: 200,
|
||||||
usage: Usage::default(),
|
usage: Usage::default(),
|
||||||
session,
|
session,
|
||||||
@@ -107,6 +109,15 @@ impl Agent {
|
|||||||
self.model = model.into();
|
self.model = model.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn effort(&self) -> hx_ai::Effort {
|
||||||
|
self.effort
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Thinking level for the following requests.
|
||||||
|
pub fn set_effort(&mut self, e: hx_ai::Effort) {
|
||||||
|
self.effort = e;
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_system(&mut self, system: impl Into<String>) {
|
pub fn set_system(&mut self, system: impl Into<String>) {
|
||||||
self.system = system.into();
|
self.system = system.into();
|
||||||
}
|
}
|
||||||
@@ -239,6 +250,7 @@ impl Agent {
|
|||||||
messages: view.messages,
|
messages: view.messages,
|
||||||
tools: self.tools.specs(),
|
tools: self.tools.specs(),
|
||||||
max_tokens: self.max_tokens,
|
max_tokens: self.max_tokens,
|
||||||
|
effort: self.effort,
|
||||||
};
|
};
|
||||||
let mut s = self.provider.stream(req).await?;
|
let mut s = self.provider.stream(req).await?;
|
||||||
let mut done = None;
|
let mut done = None;
|
||||||
|
|||||||
@@ -56,6 +56,11 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
|
|||||||
"switch provider",
|
"switch provider",
|
||||||
Enum(vec!["claude".into(), "codex".into()]),
|
Enum(vec!["claude".into(), "codex".into()]),
|
||||||
),
|
),
|
||||||
|
b(
|
||||||
|
"effort",
|
||||||
|
"thinking level (tab on an empty line cycles)",
|
||||||
|
Enum(["off", "low", "medium", "high"].map(String::from).into()),
|
||||||
|
),
|
||||||
b("compact", "summarize old context", None),
|
b("compact", "summarize old context", None),
|
||||||
b("new", "start a new session (old one stays resumable)", None),
|
b("new", "start a new session (old one stays resumable)", None),
|
||||||
b("clear", "alias of /new", None),
|
b("clear", "alias of /new", None),
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ impl Plan {
|
|||||||
messages: vec![Message::user(self.transcript.clone())],
|
messages: vec![Message::user(self.transcript.clone())],
|
||||||
tools: vec![],
|
tools: vec![],
|
||||||
max_tokens: 4096,
|
max_tokens: 4096,
|
||||||
|
effort: hx_ai::Effort::Off,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -183,6 +183,10 @@ impl App {
|
|||||||
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
|
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
|
||||||
self.st.kind = sw.kind;
|
self.st.kind = sw.kind;
|
||||||
self.st.model = sw.model.clone();
|
self.st.model = sw.model.clone();
|
||||||
|
// keep the level when the new provider has it, else its first (Codex has no "off")
|
||||||
|
if !hx_ai::Effort::levels(sw.kind).contains(&self.st.effort) {
|
||||||
|
self.st.effort = hx_ai::Effort::levels(sw.kind)[0];
|
||||||
|
}
|
||||||
if sw.provider_changed {
|
if sw.provider_changed {
|
||||||
self.st.quota = None;
|
self.st.quota = None;
|
||||||
}
|
}
|
||||||
@@ -298,6 +302,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
|||||||
st: status::Status {
|
st: status::Status {
|
||||||
kind: switcher.kind(),
|
kind: switcher.kind(),
|
||||||
model: agent.model().to_string(),
|
model: agent.model().to_string(),
|
||||||
|
effort: agent.effort(),
|
||||||
usage: Usage::default(),
|
usage: Usage::default(),
|
||||||
ctx_tokens: agent.context_tokens(),
|
ctx_tokens: agent.context_tokens(),
|
||||||
ctx_max: agent.compact_at(),
|
ctx_max: agent.compact_at(),
|
||||||
@@ -906,6 +911,10 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
|||||||
KeyCode::End => app.ed.end(),
|
KeyCode::End => app.ed.end(),
|
||||||
KeyCode::Up => app.ed.up(),
|
KeyCode::Up => app.ed.up(),
|
||||||
KeyCode::Down => app.ed.down(),
|
KeyCode::Down => app.ed.down(),
|
||||||
|
KeyCode::Tab if app.ed.buf.is_empty() => {
|
||||||
|
app.st.effort = app.st.effort.next(app.st.kind);
|
||||||
|
app.hint = format!("thinking: {}", app.st.effort.name());
|
||||||
|
}
|
||||||
KeyCode::Tab => {
|
KeyCode::Tab => {
|
||||||
let c = completion(app);
|
let c = completion(app);
|
||||||
let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect();
|
let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect();
|
||||||
@@ -1054,6 +1063,21 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
|
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"effort" if arg.is_empty() => app.t.push(Item::Info(format!(
|
||||||
|
"thinking: {} (off, low, medium, high)",
|
||||||
|
app.st.effort.name()
|
||||||
|
))),
|
||||||
|
"effort" => match arg.parse::<hx_ai::Effort>() {
|
||||||
|
Ok(e) if hx_ai::Effort::levels(app.st.kind).contains(&e) => {
|
||||||
|
app.st.effort = e;
|
||||||
|
app.t.push(Item::Info(format!("thinking → {}", e.name())));
|
||||||
|
}
|
||||||
|
Ok(_) => app.t.push(Item::Error(format!(
|
||||||
|
"{:?} cannot turn thinking off",
|
||||||
|
app.st.kind
|
||||||
|
))),
|
||||||
|
Err(e) => app.t.push(Item::Error(e)),
|
||||||
|
},
|
||||||
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
|
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
|
||||||
"model" => {
|
"model" => {
|
||||||
let mut a = agent.lock().await;
|
let mut a = agent.lock().await;
|
||||||
@@ -1147,14 +1171,11 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
|||||||
app.since = Instant::now();
|
app.since = Instant::now();
|
||||||
let prompt = expand_mentions(&line, cwd);
|
let prompt = expand_mentions(&line, cwd);
|
||||||
let (agent, tx) = (agent.clone(), tx.clone());
|
let (agent, tx) = (agent.clone(), tx.clone());
|
||||||
|
let effort = app.st.effort;
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let r = agent
|
let mut a = agent.lock().await;
|
||||||
.lock()
|
a.set_effort(effort);
|
||||||
.await
|
let r = a.run(prompt).await.map(|_| ()).map_err(|e| e.to_string());
|
||||||
.run(prompt)
|
|
||||||
.await
|
|
||||||
.map(|_| ())
|
|
||||||
.map_err(|e| e.to_string());
|
|
||||||
let _ = tx.send(Ui::Done(r));
|
let _ = tx.send(Ui::Done(r));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1799,6 +1820,7 @@ mod tests {
|
|||||||
st: status::Status {
|
st: status::Status {
|
||||||
kind: Kind::Claude,
|
kind: Kind::Claude,
|
||||||
model: "m1".into(),
|
model: "m1".into(),
|
||||||
|
effort: hx_ai::Effort::Off,
|
||||||
usage: Usage::default(),
|
usage: Usage::default(),
|
||||||
ctx_tokens: 0,
|
ctx_tokens: 0,
|
||||||
ctx_max: 150_000,
|
ctx_max: 150_000,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ use ratatui::text::{Line, Span};
|
|||||||
pub struct Status {
|
pub struct Status {
|
||||||
pub kind: Kind,
|
pub kind: Kind,
|
||||||
pub model: String,
|
pub model: String,
|
||||||
|
pub effort: hx_ai::Effort,
|
||||||
pub usage: Usage,
|
pub usage: Usage,
|
||||||
pub ctx_tokens: usize,
|
pub ctx_tokens: usize,
|
||||||
/// auto-compact threshold: the context bar's 100%
|
/// auto-compact threshold: the context bar's 100%
|
||||||
@@ -226,6 +227,9 @@ pub fn footer(st: &Status, c: &Chrome, width: u16, now: u64) -> Line<'static> {
|
|||||||
|
|
||||||
fn tail(st: &Status, c: &Chrome) -> Vec<String> {
|
fn tail(st: &Status, c: &Chrome) -> Vec<String> {
|
||||||
let mut t = vec![format!("{:?}", st.kind), st.model.clone()];
|
let mut t = vec![format!("{:?}", st.kind), st.model.clone()];
|
||||||
|
if st.effort != hx_ai::Effort::Off {
|
||||||
|
t.push(format!("think {}", st.effort.name()));
|
||||||
|
}
|
||||||
if c.queued > 0 {
|
if c.queued > 0 {
|
||||||
t.push(format!("{} queued", c.queued));
|
t.push(format!("{} queued", c.queued));
|
||||||
}
|
}
|
||||||
@@ -322,6 +326,7 @@ mod tests {
|
|||||||
Status {
|
Status {
|
||||||
kind: Kind::Claude,
|
kind: Kind::Claude,
|
||||||
model: "m1".into(),
|
model: "m1".into(),
|
||||||
|
effort: hx_ai::Effort::Off,
|
||||||
usage: Usage::default(),
|
usage: Usage::default(),
|
||||||
ctx_tokens: 0,
|
ctx_tokens: 0,
|
||||||
ctx_max: 150_000,
|
ctx_max: 150_000,
|
||||||
|
|||||||
Reference in new issue
Block a user