use std::{collections::HashMap, panic::AssertUnwindSafe, path::Path, sync::Arc};
use anyhow::Context as _;
use futures::{
FutureExt as _, StreamExt as _,
stream::{BoxStream, FuturesUnordered},
};
use tokio::sync::Mutex;
use virtx::console::ConsoleClient;
use super::{
AgentSpec, AgentState, ContextManager, image::fit_images_off_runtime, skill::render_skills,
spec::split_desc,
};
use crate::{
browser,
datatype::Value,
message::{Delta as _, FinishReason, Message, MessageDeltaOutput, MessageOutput, Part, Role},
model::{InferLangModel, LangModelOptions, RequestRefused, create_lang_model},
tool::{
ToolDesc, ToolFunc, create_tool,
r#impl::{
get_mem_insert_tool_desc, get_mem_insert_tool_func, get_mem_search_tool_desc,
get_mem_search_tool_func, get_web_search_tool_factory,
},
},
};
pub(crate) const MAX_TOOL_RESULT_CHARS: usize = 30_000;
const CUT_OFF: &str = "the model's reply was cut off at its output limit";
pub struct Agent {
model: Arc<dyn InferLangModel>,
options: LangModelOptions,
tool_descs: Vec<ToolDesc>,
tools: HashMap<String, ToolFunc>,
pub state: AgentState,
context_manager: Option<ContextManager>,
}
impl Agent {
pub async fn try_new(spec: AgentSpec) -> anyhow::Result<Self> {
Self::try_with_state(spec, AgentState::new()).await
}
pub async fn try_with_state(spec: AgentSpec, mut state: AgentState) -> anyhow::Result<Self> {
let model = create_lang_model(&spec.model).await?;
let mut tools = HashMap::with_capacity(spec.tools.len());
for desc in &spec.tools {
let func = match (&spec.web_search_engines, desc.name.as_str()) {
(Some(engines), "web_search") => {
get_web_search_tool_factory(engines.clone())(desc)?
}
_ => create_tool(desc)?,
};
tools.insert(desc.name.clone(), func);
}
let mut tool_descs = spec.tools.clone();
if let Some(memory) = state.memory.clone() {
for (desc, func) in [
(
get_mem_search_tool_desc(),
get_mem_search_tool_func(memory.clone()),
),
(get_mem_insert_tool_desc(), get_mem_insert_tool_func(memory)),
] {
tools.insert(desc.name.clone(), func);
tool_descs.push(desc);
}
}
if let Some(session) = &state.browser {
let console = state.console.lock().await.is_some();
for (desc, func) in browser::tools(session, console) {
tools.insert(desc.name.clone(), func);
tool_descs.push(desc);
}
}
if !state.history.iter().any(|m| m.role == Role::System) {
let skills = if spec.skills.is_empty() {
None
} else {
let org = split_desc(&spec.model).0;
Some(render_skills(&spec.skills, &state.console, org).await?)
};
let text = [spec.instruction, skills]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join("\n\n");
if !text.is_empty() {
state.history.insert(
0,
Message::new(Role::System).with_contents([Part::text(text)]),
);
}
}
Ok(Self {
model,
options: spec.model_options.unwrap_or_default(),
tool_descs,
tools,
state,
context_manager: None,
})
}
pub fn history(&self) -> &[Message] {
&self.state.history
}
pub fn context_manager(&self) -> Option<&ContextManager> {
self.context_manager.as_ref()
}
pub fn set_context_manager(&mut self, context_manager: Option<ContextManager>) {
self.context_manager = context_manager;
}
fn manage_context(&mut self) {
if let Some(cm) = &self.context_manager
&& cm.max_input_tokens > 0
&& self.state.last_input_tokens.unwrap_or(0) > cm.max_input_tokens
{
cm.truncate_history(&mut self.state.history);
}
}
fn commit(&mut self, output: &MessageOutput) {
if let Some(usage) = &output.usage {
self.state.last_input_tokens = Some(usage.input_tokens);
}
self.state.history.push(output.message.clone());
}
pub fn run(&mut self, query: Message) -> BoxStream<'_, anyhow::Result<MessageOutput>> {
Box::pin(async_stream::try_stream! {
self.begin_turn(query).await;
let mut committed = false;
let mut refused: Option<Vec<Message>> = None;
loop {
let output = match self
.model
.infer(&self.state.history, &self.tool_descs, &self.options)
.await
{
Ok(output) => output,
Err(e) => {
if let Some(saved) = refused.take() {
restore_results(&mut self.state.history, saved);
} else if let Some(saved) = mend_refusal(&mut self.state.history, &e) {
refused = Some(saved);
continue;
}
if !committed {
self.state.history.pop();
}
Err(e)?
}
};
refused = None;
self.commit(&output);
committed = true;
let calls = tool_calls(&output);
let cut_off = matches!(output.finish_reason, FinishReason::Length {});
yield output;
if cut_off {
Err(anyhow::anyhow!(CUT_OFF))?;
}
if calls.is_empty() {
break;
}
let mut results = self.call_tools(calls);
while let Some(message) = results.next().await {
let message = message?;
self.state.history.push(message.clone());
yield tool_output(message);
}
}
})
}
pub fn run_stream(
&mut self,
query: Message,
) -> BoxStream<'_, anyhow::Result<MessageDeltaOutput>> {
Box::pin(async_stream::try_stream! {
self.begin_turn(query).await;
let mut committed = false;
let mut refused: Option<Vec<Message>> = None;
loop {
let mut deltas =
self.model
.infer_stream(&self.state.history, &self.tool_descs, &self.options);
let mut acc = MessageDeltaOutput::new();
let mut failure = None;
while let Some(delta) = deltas.next().await {
let step = delta.and_then(|delta| {
let prev = std::mem::replace(&mut acc, MessageDeltaOutput::new());
acc = prev.accumulate(delta.clone())?;
Ok(delta)
});
match step {
Ok(delta) => yield delta,
Err(e) => {
failure = Some(e);
break;
}
}
}
let output = match failure.map_or_else(|| acc.finish(), Err) {
Ok(output) => output,
Err(e) => {
if let Some(saved) = refused.take() {
restore_results(&mut self.state.history, saved);
} else if let Some(saved) = mend_refusal(&mut self.state.history, &e) {
refused = Some(saved);
continue;
}
if !committed {
self.state.history.pop();
}
Err(e)?
}
};
refused = None;
self.commit(&output);
committed = true;
if matches!(output.finish_reason, FinishReason::Length {}) {
Err(anyhow::anyhow!(CUT_OFF))?;
}
let calls = tool_calls(&output);
if calls.is_empty() {
break;
}
let mut results = self.call_tools(calls);
while let Some(message) = results.next().await {
let message = message?;
self.state.history.push(message.clone());
yield tool_output(message).into();
}
}
})
}
async fn begin_turn(&mut self, mut query: Message) {
close_dangling_calls(&mut self.state.history);
let default = ContextManager::default();
let cm = self.context_manager.as_ref().unwrap_or(&default);
cm.cap_images(&mut self.state.history);
if let Some(note) = self.state.browser.as_ref().and_then(|b| b.catch_up()) {
query.contents.insert(0, Part::text(note));
}
let query = fit_images_off_runtime(query).await;
self.state.history.push(query);
self.manage_context();
self.seed_mounts().await;
}
pub async fn start_browser(&mut self) -> anyhow::Result<()> {
self.state
.browser
.clone()
.context("this agent has no browser")?
.start()
.await
}
async fn seed_mounts(&mut self) {
let mounts: Vec<std::path::PathBuf> = match self.state.console.lock().await.as_ref() {
Some(console) => console.mounts().map(Path::to_path_buf).collect(),
None => return,
};
if mounts.is_empty() {
return;
}
let mut section = String::from(
"# Mounts\n\nThe directories you have been given, in the order they were mounted:\n",
);
for path in &mounts {
section.push_str(&format!("\n- `{}`", path.display()));
}
let Some(system) = self
.state
.history
.iter_mut()
.find(|m| m.role == Role::System)
else {
self.state.history.insert(
0,
Message::new(Role::System).with_contents([Part::text(section)]),
);
return;
};
let text = system.contents.iter_mut().find_map(|p| match p {
Part::Text { text } => Some(text),
_ => None,
});
match text {
Some(text) if text.contains(§ion) => {}
Some(text) => {
text.push_str("\n\n");
text.push_str(§ion);
}
None => system.contents.insert(0, Part::text(section)),
}
}
fn call_tools(&self, calls: Vec<Part>) -> BoxStream<'static, anyhow::Result<Message>> {
let calls: Vec<_> = calls
.iter()
.filter_map(Part::as_function)
.map(|(id, name, args)| {
(
id.to_owned(),
name.to_owned(),
args.clone(),
self.tools.get(name).cloned(),
)
})
.collect();
let needs_console = calls
.iter()
.any(|(.., tool)| tool.as_ref().is_some_and(ToolFunc::needs_console));
let console = self.state.console.clone();
Box::pin(async_stream::try_stream! {
if needs_console && let Some(console) = console.lock().await.as_mut() {
console.start().await?;
}
let mut pending: FuturesUnordered<_> = calls
.into_iter()
.map(|(id, name, args, tool)| call_tool(id, name, args, tool, console.clone()))
.collect();
while let Some(message) = pending.next().await {
yield message;
}
if needs_console && let Some(console) = console.lock().await.as_mut() {
console.stop().await?;
}
})
}
}
fn tool_calls(output: &MessageOutput) -> Vec<Part> {
match output.finish_reason {
FinishReason::ToolCall {} => output.message.tool_calls.clone().unwrap_or_default(),
_ => Vec::new(),
}
}
fn tool_output(message: Message) -> MessageOutput {
MessageOutput {
message,
finish_reason: FinishReason::Stop {},
usage: None,
}
}
fn close_dangling_calls(history: &mut Vec<Message>) {
let Some(at) = history.iter().rposition(|m| m.role == Role::Assistant) else {
return;
};
let answered = history[at + 1..]
.iter()
.take_while(|m| m.role == Role::Tool)
.count();
let results: Vec<Message> = history[at]
.tool_calls
.iter()
.flatten()
.filter_map(Part::as_function)
.map(|(id, ..)| id)
.filter(|id| {
!history[at + 1..at + 1 + answered]
.iter()
.any(|m| m.id.as_deref() == Some(*id))
})
.map(|id| tool_error(id.to_owned(), "the call was interrupted before it returned"))
.collect();
let end = at + 1 + answered;
history.splice(end..end, results);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Refused {
LastImages,
#[allow(dead_code)]
LastTexts,
#[allow(dead_code)]
OlderImages,
#[allow(dead_code)]
TooLong,
}
impl Refused {
fn diagnose(refused: &RequestRefused) -> Option<Self> {
let message = refused.message.to_lowercase();
if message.contains("image") {
return Some(Self::LastImages);
}
None
}
fn mend(self, history: &mut [Message], refused: &RequestRefused) -> Option<Vec<Message>> {
match self {
Self::LastImages => replace_last_parts(history, Part::is_image, "image", refused),
Self::LastTexts | Self::OlderImages | Self::TooLong => None,
}
}
}
fn replace_last_parts(
history: &mut [Message],
is_refused: fn(&Part) -> bool,
what: &str,
refused: &RequestRefused,
) -> Option<Vec<Message>> {
let from = history
.iter()
.rposition(|m| m.role != Role::Tool)
.map_or(0, |i| i + 1);
let results = &mut history[from..];
if !results.iter().flat_map(|m| &m.contents).any(is_refused) {
return None;
}
let saved = results.to_vec();
let text = middle_truncate(
&format!(
"The model's API refused this {what}, so it was dropped; return it another way, \
or go on without it. The API said: {refused}"
),
MAX_TOOL_RESULT_CHARS,
);
for part in results.iter_mut().flat_map(|m| &mut m.contents) {
if is_refused(part) {
*part = Part::text(text.clone());
}
}
Some(saved)
}
fn mend_refusal(history: &mut [Message], error: &anyhow::Error) -> Option<Vec<Message>> {
let refused = error.downcast_ref::<RequestRefused>()?;
Refused::diagnose(refused)?.mend(history, refused)
}
fn restore_results(history: &mut [Message], saved: Vec<Message>) {
let from = history.len() - saved.len();
history[from..].clone_from_slice(&saved);
}
fn tool_error(id: String, text: impl Into<String>) -> Message {
Message::new(Role::Tool)
.with_contents([Part::text(text)])
.with_id(id)
}
async fn call_tool(
id: String,
name: String,
args: Value,
tool: Option<ToolFunc>,
console: Arc<Mutex<Option<ConsoleClient>>>,
) -> Message {
let Some(tool) = tool else {
return tool_error(id, format!("there is no tool named '{name}'"));
};
async fn last<T>(_: Option<T>, item: T) -> Option<T> {
Some(item)
}
let call_id = id.clone();
let run = async move {
match tool.call_pure(args.clone(), call_id.clone()) {
Some(stream) => Ok(stream.fold(None, last).await),
None => {
let mut guard = console.lock().await;
let Some(console) = guard.as_mut() else {
return Err("it needs a console, and the agent has none; \
give it one with `AgentState::with_console`");
};
Ok(tool.call(args, call_id, console).fold(None, last).await)
}
}
};
let mut message = match AssertUnwindSafe(run).catch_unwind().await {
Ok(Ok(Some(output))) => output.message,
Ok(Ok(None)) => return tool_error(id, format!("tool '{name}' produced no output")),
Ok(Err(e)) => return tool_error(id, format!("tool '{name}' failed: {e}")),
Err(_) => return tool_error(id, format!("tool '{name}' panicked")),
};
message.role = Role::Tool;
message.id.get_or_insert(id);
cap_tool_result(fit_images_off_runtime(message).await)
}
fn cap_tool_result(mut message: Message) -> Message {
for part in &mut message.contents {
match part {
Part::Value { value } if !fits_tool_result(value) => {
let json = serde_json::to_string(value).unwrap_or_default();
*value = Value::string(middle_truncate(&json, MAX_TOOL_RESULT_CHARS));
}
Part::Text { text } if text.len() > MAX_TOOL_RESULT_CHARS => {
*text = middle_truncate(text, MAX_TOOL_RESULT_CHARS);
}
_ => {}
}
}
message
}
pub(crate) fn fits_tool_result(value: &Value) -> bool {
serde_json::to_string(value)
.unwrap_or_default()
.chars()
.count()
<= MAX_TOOL_RESULT_CHARS
}
fn middle_truncate(s: &str, max_chars: usize) -> String {
let len = s.chars().count();
if len <= max_chars {
return s.to_owned();
}
let head = max_chars / 2;
let tail = max_chars - head;
let head_str: String = s.chars().take(head).collect();
let tail_str: String = s.chars().skip(len - tail).collect();
format!(
"{head_str}\n\n... [{} characters omitted] ...\n\n{tail_str}",
len - head - tail
)
}
#[cfg(test)]
mod tests {
use std::{collections::VecDeque, sync::Mutex as StdMutex};
use futures::{
future::BoxFuture,
stream::{self, BoxStream},
};
use super::*;
use crate::agent::context::IMAGE_PLACEHOLDER;
use crate::{
datatype::Bytes,
message::{Role, TokenUsage},
model::{LangModelProvider, set_lang_model_provider},
suppress_panics, to_value,
tool::{ToolDescBuilder, ToolProvider, set_tool_provider},
tool_func,
};
#[derive(Default)]
struct ScriptedModel {
outputs: StdMutex<VecDeque<anyhow::Result<MessageOutput>>>,
seen: StdMutex<Vec<Vec<Message>>>,
}
impl ScriptedModel {
fn next(&self, messages: &[Message]) -> anyhow::Result<MessageOutput> {
self.seen.lock().unwrap().push(messages.to_vec());
self.outputs
.lock()
.unwrap()
.pop_front()
.unwrap_or_else(|| Err(anyhow::anyhow!("the script has run out")))
}
}
impl InferLangModel for ScriptedModel {
fn infer(
&self,
messages: &[Message],
_: &[ToolDesc],
_: &LangModelOptions,
) -> BoxFuture<'static, anyhow::Result<MessageOutput>> {
let output = self.next(messages);
Box::pin(async move { output })
}
fn infer_stream(
&self,
messages: &[Message],
_: &[ToolDesc],
_: &LangModelOptions,
) -> BoxStream<'static, anyhow::Result<MessageDeltaOutput>> {
let output = self.next(messages).map(MessageDeltaOutput::from);
Box::pin(stream::once(async move { output }))
}
}
fn answer(text: &str) -> anyhow::Result<MessageOutput> {
Ok(MessageOutput {
message: Message::new(Role::Assistant).with_contents([Part::text(text)]),
finish_reason: FinishReason::Stop {},
usage: None,
})
}
fn cut(text: &str) -> anyhow::Result<MessageOutput> {
Ok(MessageOutput {
message: Message::new(Role::Assistant).with_contents([Part::text(text)]),
finish_reason: FinishReason::Length {},
usage: None,
})
}
fn refused() -> anyhow::Result<MessageOutput> {
Err(RequestRefused {
status: 400,
message: "X API request failed with status 400: image too large".into(),
}
.into())
}
fn calls(calls: &[(&str, &str)]) -> anyhow::Result<MessageOutput> {
Ok(MessageOutput {
message: Message::new(Role::Assistant).with_tool_calls(
calls
.iter()
.map(|(id, name)| Part::function(*id, *name, to_value!({}))),
),
finish_reason: FinishReason::ToolCall {},
usage: None,
})
}
fn scripted(
name: &str,
script: impl IntoIterator<Item = anyhow::Result<MessageOutput>>,
) -> (Arc<ScriptedModel>, AgentSpec) {
let model = Arc::new(ScriptedModel {
outputs: StdMutex::new(script.into_iter().collect()),
..Default::default()
});
let shared = model.clone();
set_lang_model_provider(
name,
LangModelProvider::custom(move |_, _| Ok(shared.clone())),
);
set_tool_provider(
"echo",
tool_func!(|_args: Value| -> Value { Value::string("echoed") }),
);
set_tool_provider(
"shot",
tool_func!(|_args: Value, id: String| -> Message {
let image = Part::image_embedded("image/png", Bytes::from(vec![0u8; 4])).unwrap();
Message::new(Role::Tool)
.with_contents([Part::text("the page"), image])
.with_id(id)
}),
);
set_tool_provider(
"boom",
tool_func!(|_args: Value| -> Value {
if true {
panic!("boom");
}
Value::Null
}),
);
set_tool_provider(
"console_only",
tool_func!(async |_args: Value, _console: &mut ConsoleClient| -> Value { Value::Null }),
);
let tool = |name: &str| {
ToolDescBuilder::new(name)
.parameters(to_value!({"type": "object", "properties": {}}))
.build()
};
let spec = AgentSpec::new(format!("{name}/any"))
.instruction("Be brief.")
.tools([
tool("echo"),
tool("shot"),
tool("boom"),
tool("console_only"),
]);
(model, spec)
}
fn user(text: &str) -> Message {
Message::new(Role::User).with_contents([Part::text(text)])
}
fn roles(history: &[Message]) -> Vec<Role> {
history.iter().map(|m| m.role.clone()).collect()
}
fn text_of(message: &Message) -> String {
message
.contents
.iter()
.filter_map(|p| p.as_text())
.collect()
}
fn images_in(history: &[Message]) -> usize {
history
.iter()
.flat_map(|m| &m.contents)
.filter(|p| p.is_image())
.count()
}
#[tokio::test]
async fn test_run_calls_tools_until_the_model_answers() {
let name = "test-agent-run";
let (model, spec) = scripted(name, [calls(&[("c1", "echo")]), answer("done")]);
let mut agent = Agent::try_new(spec).await.unwrap();
let outputs: Vec<_> = agent.run(user("hi")).map(Result::unwrap).collect().await;
assert_eq!(
roles(
&outputs
.iter()
.map(|o| o.message.clone())
.collect::<Vec<_>>()
),
[Role::Assistant, Role::Tool, Role::Assistant]
);
assert_eq!(outputs[1].message.id.as_deref(), Some("c1"));
assert_eq!(
roles(agent.history()),
[
Role::System,
Role::User,
Role::Assistant,
Role::Tool,
Role::Assistant
]
);
assert_eq!(text_of(&agent.history()[0]), "Be brief.");
assert_eq!(model.seen.lock().unwrap()[1].len(), 4);
}
#[tokio::test]
async fn test_run_stream_matches_run() {
let name = "test-agent-run-stream";
let (_, spec) = scripted(name, [calls(&[("c1", "echo")]), answer("done")]);
let mut agent = Agent::try_new(spec).await.unwrap();
let deltas: Vec<_> = agent
.run_stream(user("hi"))
.map(Result::unwrap)
.collect()
.await;
assert_eq!(deltas.len(), 3);
assert_eq!(
roles(agent.history()),
[
Role::System,
Role::User,
Role::Assistant,
Role::Tool,
Role::Assistant
]
);
assert_eq!(text_of(agent.history().last().unwrap()), "done");
}
#[tokio::test]
async fn test_every_call_gets_one_result_whatever_goes_wrong() {
suppress_panics!();
let name = "test-agent-tool-errors";
let (_, spec) = scripted(
name,
[
calls(&[
("c1", "echo"),
("c2", "boom"),
("c3", "missing"),
("c4", "console_only"),
]),
answer("done"),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
agent.run(user("hi")).for_each(|_| async {}).await;
let results: HashMap<_, _> = agent
.history()
.iter()
.filter(|m| m.role == Role::Tool)
.map(|m| (m.id.clone().unwrap(), m.clone()))
.collect();
assert_eq!(results.len(), 4);
assert!(text_of(&results["c2"]).contains("panicked"));
assert!(text_of(&results["c3"]).contains("no tool named"));
assert!(text_of(&results["c4"]).contains("needs a console"));
assert_eq!(text_of(agent.history().last().unwrap()), "done");
}
#[test]
fn test_only_a_refusal_naming_an_image_is_mended() {
let diagnose = |message: &str| {
Refused::diagnose(&RequestRefused {
status: 400,
message: message.into(),
})
};
assert_eq!(
diagnose("messages.1.content.16.image.source.base64.data: dimensions exceed"),
Some(Refused::LastImages)
);
assert_eq!(
diagnose("Image exceeds 5 MB maximum"),
Some(Refused::LastImages)
);
assert_eq!(
diagnose("prompt is too long: 300024 tokens > 200000 maximum"),
None
);
assert_eq!(diagnose("API key not valid"), None);
}
#[tokio::test]
async fn test_a_refused_image_goes_back_to_the_model_as_an_error() {
let name = "test-agent-refused-image";
let (model, spec) = scripted(
name,
[
calls(&[("c1", "echo"), ("c2", "shot")]),
refused(),
answer("done"),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
let outputs: Vec<_> = agent.run(user("hi")).collect().await;
assert!(outputs.iter().all(Result::is_ok));
assert_eq!(text_of(agent.history().last().unwrap()), "done");
let results: HashMap<_, _> = agent
.history()
.iter()
.filter(|m| m.role == Role::Tool)
.map(|m| (m.id.clone().unwrap(), m.clone()))
.collect();
assert!(matches!(&results["c1"].contents[..], [Part::Value { .. }]));
assert!(matches!(
&results["c2"].contents[..],
[Part::Text { .. }, Part::Text { .. }]
));
assert_eq!(results["c2"].contents[0].as_text(), Some("the page"));
assert!(text_of(&results["c2"]).contains("image too large"));
let seen = model.seen.lock().unwrap();
assert_eq!(seen.len(), 3);
assert!(text_of(seen[2].last().unwrap()).contains("image too large"));
}
#[tokio::test]
async fn test_a_second_refusal_ends_the_turn_with_the_results_as_they_were() {
let name = "test-agent-refused-twice";
let (_, spec) = scripted(name, [calls(&[("c1", "shot")]), refused(), refused()]);
let mut agent = Agent::try_new(spec).await.unwrap();
let outputs: Vec<_> = agent.run(user("hi")).collect().await;
assert!(outputs.last().unwrap().is_err());
assert_eq!(
roles(agent.history()),
[Role::System, Role::User, Role::Assistant, Role::Tool]
);
assert!(matches!(
&agent.history()[3].contents[..],
[Part::Text { .. }, Part::Image { .. }]
));
}
#[tokio::test]
async fn test_a_refused_image_outside_the_last_batch_keeps_the_results() {
let name = "test-agent-refused-elsewhere";
let (model, spec) = scripted(name, [calls(&[("c1", "echo")]), refused()]);
let mut agent = Agent::try_new(spec).await.unwrap();
let outputs: Vec<_> = agent.run(user("hi")).collect().await;
assert!(outputs.last().unwrap().is_err());
assert_eq!(model.seen.lock().unwrap().len(), 2);
assert!(matches!(
&agent.history()[3].contents[..],
[Part::Value { .. }]
));
}
#[tokio::test]
async fn test_any_other_failure_after_tools_keeps_their_results() {
let name = "test-agent-failed-after-tools";
let (_, spec) = scripted(
name,
[calls(&[("c1", "echo")]), Err(anyhow::anyhow!("down"))],
);
let mut agent = Agent::try_new(spec).await.unwrap();
let outputs: Vec<_> = agent.run(user("hi")).collect().await;
assert!(outputs.last().unwrap().is_err());
assert!(matches!(
&agent.history()[3].contents[..],
[Part::Value { .. }]
));
}
#[tokio::test]
async fn test_run_stream_hands_a_refused_image_back_too() {
let name = "test-agent-refused-image-stream";
let (_, spec) = scripted(name, [calls(&[("c1", "shot")]), refused(), answer("done")]);
let mut agent = Agent::try_new(spec).await.unwrap();
let deltas: Vec<_> = agent.run_stream(user("hi")).collect().await;
assert!(deltas.iter().all(Result::is_ok));
assert_eq!(text_of(agent.history().last().unwrap()), "done");
assert!(text_of(&agent.history()[3]).contains("refused"));
}
#[tokio::test]
async fn test_a_cut_off_reply_ends_the_turn_with_an_error() {
let name = "test-agent-cut-off";
let (_, spec) = scripted(name, [cut("half"), answer("rest")]);
let mut agent = Agent::try_new(spec).await.unwrap();
let outputs: Vec<_> = agent.run(user("hi")).collect().await;
assert_eq!(outputs.len(), 2);
assert_eq!(text_of(&outputs[0].as_ref().unwrap().message), "half");
assert!(
outputs[1]
.as_ref()
.unwrap_err()
.to_string()
.contains("cut off")
);
assert_eq!(
roles(agent.history()),
[Role::System, Role::User, Role::Assistant]
);
let deltas: Vec<_> = agent.run_stream(user("go on")).collect().await;
assert!(deltas.iter().all(Result::is_ok));
assert_eq!(text_of(agent.history().last().unwrap()), "rest");
}
#[tokio::test]
async fn test_run_stream_ends_a_cut_off_reply_with_an_error() {
let name = "test-agent-cut-off-stream";
let (_, spec) = scripted(name, [cut("half")]);
let mut agent = Agent::try_new(spec).await.unwrap();
let deltas: Vec<_> = agent.run_stream(user("hi")).collect().await;
assert!(deltas.last().unwrap().is_err());
assert_eq!(
roles(agent.history()),
[Role::System, Role::User, Role::Assistant]
);
}
#[tokio::test]
async fn test_a_failed_turn_takes_its_query_back() {
let name = "test-agent-rollback";
let (_, spec) = scripted(name, [Err(anyhow::anyhow!("down")), answer("up")]);
let mut agent = Agent::try_new(spec).await.unwrap();
assert!(agent.run(user("first")).next().await.unwrap().is_err());
assert_eq!(roles(agent.history()), [Role::System]);
let outputs: Vec<_> = agent.run_stream(user("second")).collect().await;
assert!(outputs.iter().all(Result::is_ok));
assert_eq!(
roles(agent.history()),
[Role::System, Role::User, Role::Assistant]
);
}
#[tokio::test]
async fn test_a_given_system_message_is_kept() {
let name = "test-agent-system";
let (_, spec) = scripted(name, []);
let state = AgentState::new()
.with_history([Message::new(Role::System).with_contents([Part::text("Mine.")])]);
let agent = Agent::try_with_state(spec, state).await.unwrap();
assert_eq!(agent.history().len(), 1);
assert_eq!(text_of(&agent.history()[0]), "Mine.");
}
#[tokio::test]
async fn test_a_missing_tool_fails_construction() {
let name = "test-agent-missing-tool";
let (_, spec) = scripted(name, []);
let spec = spec.tool(ToolDescBuilder::new("nowhere").build());
assert!(Agent::try_new(spec).await.is_err());
}
#[tokio::test]
async fn test_a_failing_tool_factory_fails_construction() {
let name = "test-agent-failing-factory";
let (_, spec) = scripted(name, []);
set_tool_provider(
"refusing",
ToolProvider::function(|_| Err(anyhow::anyhow!("not today"))),
);
let spec = spec.tool(ToolDescBuilder::new("refusing").build());
let err = Agent::try_new(spec).await.err().unwrap();
assert!(err.to_string().contains("not today"), "{err}");
}
fn with_input(
output: anyhow::Result<MessageOutput>,
input_tokens: u64,
) -> anyhow::Result<MessageOutput> {
output.map(|output| MessageOutput {
usage: Some(TokenUsage {
input_tokens,
..TokenUsage::default()
}),
..output
})
}
#[tokio::test]
async fn test_context_manager_truncates_once_input_grows_past_its_limit() {
let name = "test-agent-context";
let (model, spec) = scripted(
name,
[
with_input(calls(&[("c1", "echo")]), 10),
with_input(answer("one"), 200),
with_input(answer("two"), 10),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
agent.set_context_manager(Some(ContextManager {
max_input_tokens: 100,
preserve_recent_turns: 1,
..Default::default()
}));
agent.run(user("first")).for_each(|_| async {}).await;
agent.run(user("second")).for_each(|_| async {}).await;
let seen = model.seen.lock().unwrap();
let result = seen[2].iter().find(|m| m.role == Role::Tool).unwrap();
assert_eq!(text_of(result), "[context truncated]");
assert_eq!(result.id.as_deref(), Some("c1"));
let result = seen[1].iter().find(|m| m.role == Role::Tool).unwrap();
assert_ne!(text_of(result), "[context truncated]");
}
#[tokio::test]
async fn test_a_token_limit_of_zero_truncates_nothing() {
let name = "test-agent-context-off";
let (model, spec) = scripted(
name,
[
with_input(calls(&[("c1", "echo")]), 10),
with_input(answer("one"), 200),
with_input(answer("two"), 10),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
agent.set_context_manager(Some(ContextManager {
max_input_tokens: 0,
preserve_recent_turns: 1,
..Default::default()
}));
agent.run(user("first")).for_each(|_| async {}).await;
agent.run(user("second")).for_each(|_| async {}).await;
let seen = model.seen.lock().unwrap();
let result = seen[2].iter().find(|m| m.role == Role::Tool).unwrap();
assert_ne!(text_of(result), "[context truncated]");
}
#[tokio::test]
async fn test_truncation_waits_for_the_next_turn() {
for (stream, preserve) in [(false, 1), (true, 1), (false, 0), (true, 0)] {
let name = format!("test-agent-context-mid-turn-{stream}-{preserve}");
let (model, spec) = scripted(
&name,
[
with_input(calls(&[("c1", "echo")]), 10),
with_input(answer("one"), 10),
with_input(calls(&[("c2", "echo")]), 200),
with_input(answer("two"), 210),
with_input(answer("three"), 10),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
agent.set_context_manager(Some(ContextManager {
max_input_tokens: 100,
preserve_recent_turns: preserve,
..Default::default()
}));
for query in ["first", "second", "third"] {
if stream {
agent.run_stream(user(query)).for_each(|_| async {}).await;
} else {
agent.run(user(query)).for_each(|_| async {}).await;
}
}
let seen = model.seen.lock().unwrap();
let cut = |request: &[Message]| -> Vec<bool> {
request
.iter()
.filter(|m| m.role == Role::Tool)
.map(|m| text_of(m) == "[context truncated]")
.collect()
};
let row = format!("stream: {stream}, preserve: {preserve}");
assert_eq!(cut(&seen[3]), [false, false], "{row}");
assert_eq!(cut(&seen[4]), [true, true], "{row}");
}
}
#[tokio::test]
async fn test_context_manager_replaces_old_images_at_the_start_of_a_turn() {
let name = "test-agent-images";
let (model, spec) = scripted(
name,
[
calls(&[("c1", "shot")]),
calls(&[("c2", "shot")]),
calls(&[("c3", "shot")]),
answer("one"),
answer("two"),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
agent.set_context_manager(Some(ContextManager {
max_images: 2,
preserve_recent_images: 1,
..Default::default()
}));
agent.run(user("first")).for_each(|_| async {}).await;
assert_eq!(images_in(&model.seen.lock().unwrap()[3]), 3);
assert_eq!(images_in(agent.history()), 3);
agent.run(user("second")).for_each(|_| async {}).await;
let seen = model.seen.lock().unwrap();
assert_eq!(images_in(&seen[4]), 1);
let results: Vec<_> = seen[4].iter().filter(|m| m.role == Role::Tool).collect();
assert_eq!(text_of(results[0]), format!("the page{IMAGE_PLACEHOLDER}"));
assert_eq!(text_of(results[1]), format!("the page{IMAGE_PLACEHOLDER}"));
assert!(results[2].contents[1].is_image());
}
#[tokio::test]
async fn test_images_are_capped_at_the_default_without_a_context_manager() {
let name = "test-agent-images-default";
let default = ContextManager::default();
let shots: Vec<_> = (0..=default.max_images)
.map(|n| calls(&[(&format!("c{n}"), "shot")]))
.collect();
let (model, spec) = scripted(
name,
shots.into_iter().chain([answer("one"), answer("two")]),
);
let mut agent = Agent::try_new(spec).await.unwrap();
assert!(agent.context_manager().is_none());
agent.run(user("first")).for_each(|_| async {}).await;
agent.run(user("second")).for_each(|_| async {}).await;
let seen = model.seen.lock().unwrap();
assert_eq!(
images_in(seen.last().unwrap()),
default.preserve_recent_images
);
}
#[tokio::test]
async fn test_the_query_keeps_its_images() {
let name = "test-agent-query-images";
let (model, spec) = scripted(
name,
[
calls(&[("c1", "shot")]),
calls(&[("c2", "shot")]),
answer("one"),
answer("two"),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
agent.set_context_manager(Some(ContextManager {
max_images: 1,
preserve_recent_images: 0,
..Default::default()
}));
let query = |text: &str| {
let image = Part::image_embedded("image/png", Bytes::from(vec![0u8; 4])).unwrap();
Message::new(Role::User).with_contents([Part::text(text), image.clone(), image])
};
agent.run(query("first")).for_each(|_| async {}).await;
agent.run(query("second")).for_each(|_| async {}).await;
let seen = model.seen.lock().unwrap();
let request = seen.last().unwrap();
assert_eq!(images_in(request), 4);
assert!(
request.last().unwrap().contents[1..]
.iter()
.all(Part::is_image)
);
}
#[tokio::test]
async fn test_an_image_past_the_edge_is_fitted_on_its_way_in() {
fn big_png() -> Part {
let mut out = Vec::new();
image::DynamicImage::ImageRgb8(image::RgbImage::new(3000, 10))
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
.unwrap();
Part::image_embedded("image/png", Bytes::from(out)).unwrap()
}
fn width(part: &Part) -> u32 {
let Part::Image {
image: crate::message::PartImage::Embedded { data, .. },
} = part
else {
panic!("not an embedded image");
};
image::load_from_memory(data.as_ref()).unwrap().width()
}
let name = "test-agent-fit";
let (model, spec) = scripted(name, [calls(&[("c1", "big_shot")]), answer("one")]);
set_tool_provider(
"big_shot",
tool_func!(|_args: Value, id: String| -> Message {
Message::new(Role::Tool)
.with_contents([big_png()])
.with_id(id)
}),
);
let spec = spec.tool(
ToolDescBuilder::new("big_shot")
.parameters(to_value!({"type": "object", "properties": {}}))
.build(),
);
let mut agent = Agent::try_new(spec).await.unwrap();
let query = Message::new(Role::User).with_contents([Part::text("look"), big_png()]);
agent.run(query).for_each(|_| async {}).await;
let seen = model.seen.lock().unwrap();
let widths: Vec<u32> = seen
.last()
.unwrap()
.iter()
.flat_map(|m| &m.contents)
.filter(|p| p.is_image())
.map(width)
.collect();
assert_eq!(widths, [2576, 2576]);
}
#[tokio::test]
async fn test_a_failed_turn_leaves_the_images_replaced() {
for streamed in [false, true] {
let name = format!("test-agent-images-failed-{streamed}");
let (_, spec) = scripted(
&name,
[
calls(&[("c1", "shot")]),
calls(&[("c2", "shot")]),
with_input(answer("one"), 200),
Err(anyhow::anyhow!("overloaded")),
],
);
let mut agent = Agent::try_new(spec).await.unwrap();
agent.set_context_manager(Some(ContextManager {
max_input_tokens: 100,
preserve_recent_turns: 1,
max_images: 1,
preserve_recent_images: 0,
}));
agent.run(user("first")).for_each(|_| async {}).await;
let turns = agent.history().len();
let failed = if streamed {
let outputs: Vec<_> = agent.run_stream(user("second")).collect().await;
outputs.last().unwrap().is_err()
} else {
let outputs: Vec<_> = agent.run(user("second")).collect().await;
outputs.last().unwrap().is_err()
};
assert!(failed, "streamed: {streamed}");
assert_eq!(agent.history().len(), turns, "streamed: {streamed}");
assert_eq!(images_in(agent.history()), 0, "streamed: {streamed}");
}
}
#[test]
fn test_cap_tool_result_changes_only_a_part_over_the_limit() {
let max = MAX_TOOL_RESULT_CHARS;
for (row, part, kept) in [
(
"a, max - 2",
Part::value(Value::string("a".repeat(max - 2))),
true,
),
(
"a, max - 1",
Part::value(Value::string("a".repeat(max - 1))),
false,
),
(
"가, max - 2",
Part::value(Value::string("가".repeat(max - 2))),
true,
),
(
"가, max - 1",
Part::value(Value::string("가".repeat(max - 1))),
false,
),
(
"object",
Part::value(to_value!({"text": "가".repeat(12_000)})),
true,
),
("text, max", Part::text("가".repeat(max)), true),
("text, max + 1", Part::text("가".repeat(max + 1)), false),
] {
if let Part::Value { value } = &part {
assert_eq!(fits_tool_result(value), kept, "{row}");
}
let capped = cap_tool_result(Message::new(Role::Tool).with_contents([part.clone()]));
assert_eq!(capped.contents[0] == part, kept, "{row}");
if !kept {
let note = "\n\n... [1 characters omitted] ...\n\n";
let cut = match &capped.contents[0] {
Part::Value { value } => value.as_str().unwrap(),
other => other.as_text().unwrap(),
};
assert!(cut.contains(note), "{row}");
assert_eq!(cut.chars().count(), max + note.chars().count(), "{row}");
}
}
}
#[test]
fn test_middle_truncate_keeps_both_ends() {
let cut = middle_truncate(&"a".repeat(10), 4);
assert!(cut.starts_with("aa\n\n... [6 characters omitted]"), "{cut}");
assert_eq!(middle_truncate("short", 10), "short");
}
}