Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ Quick Ask's `quick_shot` fails with `helper_failed` (the message is the helper's
| `hello` | `protocol` | `{protocol}` |
| `list_bots` | none | `{bots:[Bot]}` |
| `create_bot` | `name` (1 to 80 characters) | `{bot: Bot}` |
| `set_bot` | `bot`, `name?`, `instructions?` (at most 8000 characters), `stepLimit?` (a whole number, 1 to 1000), `avatar?` (at most 8 characters: the name of one of the window's icons, or an emoji or letters), `color?` (`#rrggbb` or empty) | `{}`; what is given changes; `bots_changed` follows. A `stepLimit` is sent to a running engine as `step_limit`. `webSearch?` (true or false) is kept and sent as `web_search`. `check?` is `off`, `own`, `model` (with `checkModel`, a model's name, validated as `set_model` does) or `bot` (with `checkBot`, the id of another bot of the same project, not an installed agent's, not the bot itself) and is kept: see Check before done; anything else, a model or bot that cannot be used, is `bad_request`; it is refused `no_check` for a bot on an installed agent (other than `off`), and from a device on the network `forbidden`, as is `checkModel` or `checkBot` alone. |
| `set_bot` | `bot`, `name?`, `instructions?` (at most 8000 characters), `stepLimit?` (a whole number, 1 to 1000), `avatar?` (at most 8 characters: the name of one of the window's icons, or an emoji or letters), `color?` (`#rrggbb` or empty), `fallbackModel?` (a model's name, or empty/`null` to clear) | `{}`; what is given changes; `bots_changed` follows. A `stepLimit` is sent to a running engine as `step_limit`. `webSearch?` (true or false) is kept and sent as `web_search`. `fallbackModel?` is kept, returned on `Bot` when set, and sent to a running engine as `fallback_model`: when the primary model fails due to a rate limit, quota, or server/network error before streaming output, the engine switches to `fallbackModel` for the rest of that turn and emits a `fallback` transcript event. `check?` is `off`, `own`, `model` (with `checkModel`, a model's name, validated as `set_model` does) or `bot` (with `checkBot`, the id of another bot of the same project, not an installed agent's, not the bot itself) and is kept: see Check before done; anything else, a model or bot that cannot be used, is `bad_request`; it is refused `no_check` for a bot on an installed agent (other than `off`), and from a device on the network `forbidden`, as is `checkModel` or `checkBot` alone. |
| `order_bots` | `bots`: every bot's id once, in the new order | `{}`; `list_bots` lists them so from then on |
| `delete_bot` | `bot` | `{}`: its engine and browser stop, it leaves its project, everything stored for it is forgotten, and its folder and browser profile move to the Trash, as Finder moves them (Put Back works). When its folder cannot be moved, nothing is deleted: `trash_failed` |
| `search` | `text` (1 to 200 bytes), `bot?`, `conversation?` (with `bot`), `limit?` (default 50, at most 200) | `{hits: [{bot, conversation, seq, atMs, kind, snippet}]}`: prompts (`kind` `user`) and replies (`reply`) holding `text` in any case, of one conversation, of `bot` or of all bots, newest first; `atMs` is when the entry was written. A reply is searched whole, as the chat joins its pieces; `seq` is its first piece's, the chat item's `id`. Backed by a SQLite FTS5 index kept in sync with the transcript. |
Expand Down
1 change: 1 addition & 0 deletions agentcore/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ impl Bridge {
// The agent has its own model, chosen in the agent; and no other bots to reach.
// shortcut: an installed agent keeps its own instructions; Bate's are not passed on until ACP has a place for them.
Op::SetModel { .. }
| Op::FallbackModel { .. }
| Op::Peers { .. }
| Op::SkillFolders { .. }
| Op::SkillsOff { .. }
Expand Down
8 changes: 8 additions & 0 deletions agentcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ struct Engine {
running: Option<Running>,
model: Option<String>,
effort: Option<String>,
fallback_model: Option<String>,
}

/// The model from the environment (`BATE_MODEL`), if any.
Expand Down Expand Up @@ -183,6 +184,7 @@ fn main() {
running: None,
model: default_model(),
effort: None,
fallback_model: None,
};
while let Ok(input) = rx.recv() {
match input {
Expand Down Expand Up @@ -351,6 +353,10 @@ impl Engine {
self.effort = effort;
self.respond(id, Ok(()));
}
Op::FallbackModel { model } => {
self.fallback_model = Some(model).filter(|m| !m.is_empty());
self.respond(id, Ok(()));
}
Op::Rewind { entry, fork } => {
let rewound = self.idle().and_then(|()| {
let session = self.session.as_mut().ok_or(NO_SESSION)?;
Expand Down Expand Up @@ -596,6 +602,8 @@ impl Engine {
provider,
model,
effort: self.effort.clone(),
fallback_model: self.fallback_model.clone(),
used_fallback: AtomicBool::new(false),
context,
check_back: false,
connectors: self.connectors.clone(),
Expand Down
21 changes: 18 additions & 3 deletions agentcore/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ pub struct Fail {
pub why: String,
/// A network error, a rate limit or a server error: asking again may work.
transient: bool,
/// Rate limit, quota exhaustion, server error, or network error: switching to a fallback model
/// may succeed.
pub fallback_eligible: bool,
/// True if any output delta had already been streamed to the caller before failing.
pub streamed: bool,
/// How long the server asked us to wait (`Retry-After`).
wait: Option<Duration>,
/// The long wait for a first line ran out: one more request, then no more.
Expand All @@ -57,6 +62,8 @@ impl From<String> for Fail {
Fail {
why,
transient: false,
fallback_eligible: false,
streamed: false,
wait: None,
once: false,
}
Expand All @@ -66,6 +73,7 @@ impl From<String> for Fail {
fn transient(why: String) -> Fail {
Fail {
transient: true,
fallback_eligible: true,
..Fail::from(why)
}
}
Expand Down Expand Up @@ -373,7 +381,7 @@ impl Provider {
ask: &Ask,
abort: &AtomicBool,
mut on: impl FnMut(Delta),
) -> Result<Reply, String> {
) -> Result<Reply, Fail> {
let mut retries = 0;
// The reason of a 400 that may have been the web search tool, until the request
// without it shows which it was.
Expand Down Expand Up @@ -417,7 +425,11 @@ impl Provider {
continue;
}
Err(fail) if fail.transient && !streamed && retries < RETRIES && !last => fail,
done => return done.map_err(|fail| fail.why),
Err(mut fail) => {
fail.streamed = streamed;
return Err(fail);
}
Ok(reply) => return Ok(reply),
};
let wait = fail.wait.map_or_else(
|| jitter(self.wait * 2u32.pow(retries)),
Expand Down Expand Up @@ -547,9 +559,12 @@ impl Provider {
let quota = ["usage_limit_exceeded", "insufficient_quota"]
.iter()
.any(|q| text.contains(q));
let retryable = (status.as_u16() == 429 && !quota) || status.is_server_error();
return Err(Fail {
why: format!("the model server answered {status}: {}", text.trim()),
transient: (status.as_u16() == 429 && !quota) || status.is_server_error(),
transient: retryable,
fallback_eligible: status.as_u16() == 429 || status.is_server_error(),
streamed: false,
wait: asked,
once: false,
});
Expand Down
87 changes: 66 additions & 21 deletions agentcore/src/turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ pub struct Turn {
/// The model chosen for the bot; without one, the service names it with the token.
pub model: Option<String>,
pub effort: Option<String>,
/// Backup model used for the rest of this turn if the primary model fails due to rate limits,
/// quota, or server/network errors.
pub fallback_model: Option<String>,
/// Latched once this turn switches to `fallback_model` so later rounds do not re-hit a dead primary.
pub used_fallback: AtomicBool,
/// `BATE_MODEL_CONTEXT`: the model's context size in tokens. It goes before the size that
/// comes with the `token` answer; with neither, `CONTEXT`. Compaction starts at four
/// fifths of it.
Expand Down Expand Up @@ -899,7 +904,8 @@ impl Turn {
self.stream_until(self.control.aborted_flag(), url, key, api, ask, on)
}

/// `stream` that gives up when `abort` is set.
/// `stream` that gives up when `abort` is set. On an eligible primary failure before any
/// output was streamed, switches to `fallback_model` for the rest of this turn.
fn stream_until(
&self,
abort: &AtomicBool,
Expand All @@ -909,28 +915,67 @@ impl Turn {
ask: &Ask,
mut on: impl FnMut(Delta),
) -> Result<Reply, String> {
let mut reply = self
.provider
.stream(url, key, api, ask, abort, |d| match d {
Delta::Retry { .. } => self.out.send(&event(d)),
// The provider ran it: shown like a tool call of ours, done at once.
Delta::Search { id, query, failed } => {
let mut args = Map::new();
args.insert("query".into(), query.into());
self.out.send(&Event::ToolStart {
call: id.into(),
tool: "web_search".into(),
args,
});
self.out.send(&Event::ToolEnd {
call: id.into(),
output: String::new(),
is_error: failed,
undo: None,
let mut call_stream = |ask: &Ask| -> Result<Reply, crate::model::Fail> {
self.provider
.stream(url, key, api, ask, abort, |d| match d {
Delta::Retry { .. } => self.out.send(&event(d)),
// The provider ran it: shown like a tool call of ours, done at once.
Delta::Search { id, query, failed } => {
let mut args = Map::new();
args.insert("query".into(), query.into());
self.out.send(&Event::ToolStart {
call: id.into(),
tool: "web_search".into(),
args,
});
self.out.send(&Event::ToolEnd {
call: id.into(),
output: String::new(),
is_error: failed,
undo: None,
});
}
d => on(d),
})
};
let fallback = self.fallback_model.as_deref().filter(|m| !m.is_empty());
let using_fallback = self.used_fallback.load(Ordering::Relaxed);
let effective = if using_fallback && let Some(fb) = fallback {
Ask {
model: fb,
effort: None,
..*ask
}
} else {
Ask { ..*ask }
};
let mut reply = match call_stream(&effective) {
Ok(reply) => reply,
Err(fail)
if fail.fallback_eligible
&& !fail.streamed
&& !abort.load(Ordering::SeqCst)
&& !using_fallback =>
{
if let Some(fb) = fallback.filter(|fb| *fb != ask.model) {
self.used_fallback.store(true, Ordering::Relaxed);
self.out.send(&Event::Fallback {
from: ask.model.to_owned(),
to: fb.to_owned(),
error: fail.why,
});
let backup = Ask {
model: fb,
effort: None,
..*ask
};
call_stream(&backup).map_err(|f| f.why)?
} else {
return Err(fail.why);
}
d => on(d),
})?;
}
Err(fail) => return Err(fail.why),
};
// A call given up on has no `usage` to wait for.
if !reply.aborted {
self.out.send(&Event::Usage {
Expand Down
77 changes: 77 additions & 0 deletions agentcore/tests/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3574,6 +3574,83 @@ fn a_server_error_is_asked_again_and_the_conversation_shows_it() {
assert_eq!(model.requests().len(), 2);
}

#[test]
fn falls_back_to_backup_model_after_primary_503_retries_exhaust_and_on_quota_429() {
let dir = workdir("fallback-503");
let quota_429 = b"HTTP/1.1 429 Too Many Requests\r\ncontent-type: application/json\r\nconnection: close\r\n\r\n{\"error\":{\"code\":\"usage_limit_exceeded\"}}".to_vec();
let model = Model::replay(vec![
refusal("503 Service Unavailable", ""),
refusal("503 Service Unavailable", ""),
refusal("503 Service Unavailable", ""),
refusal("503 Service Unavailable", ""),
refusal("503 Service Unavailable", ""),
refusal("503 Service Unavailable", ""),
whole("From backup after 503."),
// Turn 2: tries primary again, gets quota 429 -> switches immediately without 5 retries.
quota_429,
whole("From backup after quota."),
]);
let mut engine = Engine::start_with(&dir, &model, &[("BATE_MODEL_RETRY_MS", "1")]);
engine.open_new();
assert_eq!(
engine.request(Op::SetModel {
model: "primary-m".into(),
effort: None,
}),
None
);
assert_eq!(
engine.request(Op::FallbackModel {
model: "backup-m".into(),
}),
None
);

engine.prompt("first");
let events = engine.until(is_turn_end);
assert!(
events.iter().any(|e| matches!(
e,
Event::Fallback { from, to, error }
if from == "primary-m" && to == "backup-m" && error.contains("503")
)),
"{events:?}"
);
assert!(
events.contains(&Event::Text {
delta: "From backup after 503.".into(),
}),
"{events:?}"
);

engine.prompt("second");
let events = engine.until(is_turn_end);
assert_eq!(retries(&events).len(), 0, "quota 429 skips primary retries");
assert!(
events.iter().any(|e| matches!(
e,
Event::Fallback { from, to, error }
if from == "primary-m" && to == "backup-m" && error.contains("429")
)),
"{events:?}"
);
assert!(
events.contains(&Event::Text {
delta: "From backup after quota.".into(),
}),
"{events:?}"
);

let reqs = model.requests();
assert_eq!(reqs.len(), 9);
for req in &reqs[0..6] {
assert_eq!(req["model"], "primary-m");
}
assert_eq!(reqs[6]["model"], "backup-m");
assert_eq!(reqs[7]["model"], "primary-m");
assert_eq!(reqs[8]["model"], "backup-m");
}

#[test]
fn a_wait_the_server_asks_for_is_honoured() {
let dir = workdir("retry-after");
Expand Down
32 changes: 32 additions & 0 deletions appd/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3006,6 +3006,19 @@ impl Core {
.ok_or_else(|| bad("`webSearch` must be true or false"))?,
),
};
let fallback_model = match f.get("fallbackModel") {
None => None,
Some(Value::Null) => Some(""),
Some(v) => {
let m = v
.as_str()
.ok_or_else(|| bad("`fallbackModel` must be a string"))?;
if !m.is_empty() {
check_model(m, None).map_err(bad)?;
}
Some(m)
}
};
let check = match f.get("check").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(match v.as_str() {
Expand Down Expand Up @@ -3085,6 +3098,18 @@ impl Core {
if let Some(with) = check {
self.store.set_check(&bot, &with).map_err(internal)?;
}
if let Some(fb) = fallback_model {
self.store.set_fallback_model(&bot, fb).map_err(internal)?;
if self.engines.contains_key(&bot) {
self.send_op(
&bot,
Op::FallbackModel {
model: fb.to_owned(),
},
Waiter::Quiet,
)?;
}
}
self.broadcast(&json!({"type": "bots_changed"}));
Ok(Some(json!({})))
}
Expand Down Expand Up @@ -3716,6 +3741,9 @@ impl Core {
row["model"] = json!(model);
row["effort"] = json!(effort);
}
if let Ok(Some(fallback)) = self.store.fallback_model(bot) {
row["fallbackModel"] = json!(fallback);
}
if let Ok(Some(project)) = self.project_of(bot) {
row["project"] = json!({"id": project.id, "name": project.name});
}
Expand Down Expand Up @@ -3956,6 +3984,7 @@ impl Core {
let steps = self.store.step_limit(bot).map_err(internal)?;
let web_search = self.web_search_on(bot).map_err(internal)?;
let model = self.store.model(bot).map_err(internal)?;
let fallback_model = self.store.fallback_model(bot).map_err(internal)?;
let whole_disk = self.store.whole_disk(bot).map_err(internal)?;
let agent = self.store.agent(bot).map_err(internal)?;
if agent.is_some() && !whole_disk {
Expand Down Expand Up @@ -4116,6 +4145,9 @@ impl Core {
if let Some((model, effort)) = model {
self.send_op(bot, Op::SetModel { model, effort }, Waiter::Quiet)?;
}
if let Some(model) = fallback_model {
self.send_op(bot, Op::FallbackModel { model }, Waiter::Quiet)?;
}
if !skill_folders.is_empty() {
self.send_op(
bot,
Expand Down
Loading
Loading