use crate::{
agent::{Agent, AgentSpec, AgentState, ContextManager, Memory},
browser::{Browser, BrowserSession},
datatype::Value,
message::Message,
model::ThinkingEffort,
tool::{ToolDesc, WebSearchEngineKind},
};
pub struct AgentBuilder {
spec: AgentSpec,
history: Vec<Message>,
sandbox: Option<virtx::Sandbox>,
context_manager: Option<ContextManager>,
browser: Option<Browser>,
}
impl AgentBuilder {
pub fn new(model: impl Into<String>) -> Self {
Self {
spec: AgentSpec::new(model),
history: Vec::new(),
sandbox: None,
context_manager: None,
browser: None,
}
}
pub fn instruction(mut self, inst: impl Into<String>) -> Self {
self.spec = self.spec.instruction(inst);
self
}
pub fn tool(mut self, desc: ToolDesc) -> Self {
self.spec = self.spec.tool(desc);
self
}
pub fn tools(mut self, descs: impl IntoIterator<Item = ToolDesc>) -> Self {
self.spec = self.spec.tools(descs);
self
}
pub fn web_search_tool(mut self, engines: Vec<WebSearchEngineKind>) -> Self {
self.spec = self.spec.web_search_tool(engines);
self
}
pub fn web_fetch_tool(mut self) -> Self {
self.spec = self.spec.web_fetch_tool();
self
}
pub fn history(mut self, history: impl IntoIterator<Item = Message>) -> Self {
self.history = history.into_iter().collect();
self
}
pub fn sandbox(mut self, sandbox: virtx::Sandbox) -> Self {
self.spec = self.spec.sandbox_tools();
self.sandbox = Some(sandbox);
self
}
pub fn browser(mut self, browser: Browser) -> Self {
self.browser = Some(browser);
self
}
pub fn memory(mut self, memory: impl Into<Memory>) -> Self {
self.spec = self.spec.memory(memory);
self
}
pub fn skill(mut self, dir: impl Into<String>) -> Self {
self.spec = self.spec.skill(dir);
self
}
pub fn context_manager(mut self, spec: ContextManager) -> Self {
self.context_manager = Some(spec);
self
}
pub fn thinking_effort(mut self, effort: ThinkingEffort) -> Self {
self.spec = self.spec.thinking_effort(effort);
self
}
pub fn output_schema(mut self, schema: Value) -> Self {
self.spec = self.spec.output_schema(schema);
self
}
pub async fn build(self) -> anyhow::Result<Agent> {
let Self {
spec,
history,
sandbox,
context_manager,
browser,
} = self;
let mut state = AgentState::new().with_history(history);
if let Some(sandbox) = sandbox {
state = state.with_sandbox(sandbox);
}
if let Some(browser) = browser {
browser.check()?;
state = state.with_browser(BrowserSession::new(browser));
}
let mut agent = Agent::try_with_state(spec, state).await?;
agent.set_context_manager(context_manager);
Ok(agent)
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use futures::{future::BoxFuture, stream::BoxStream};
use super::*;
use crate::{
message::{MessageDeltaOutput, MessageOutput, Part, Role},
model::{InferLangModel, LangModelOptions, LangModelProvider, set_lang_model_provider},
test_sandbox,
};
const TEST_ORG: &str = "agent-builder-tests";
struct Unused;
impl InferLangModel for Unused {
fn infer(
&self,
_: &[Message],
_: &[ToolDesc],
_: &LangModelOptions,
) -> BoxFuture<'static, anyhow::Result<MessageOutput>> {
unimplemented!()
}
fn infer_stream(
&self,
_: &[Message],
_: &[ToolDesc],
_: &LangModelOptions,
) -> BoxStream<'static, anyhow::Result<MessageDeltaOutput>> {
unimplemented!()
}
}
fn builder() -> AgentBuilder {
set_lang_model_provider(
TEST_ORG,
LangModelProvider::custom(|_, _| Ok(Arc::new(Unused))),
);
AgentBuilder::new(format!("{TEST_ORG}/any"))
}
fn system_text(agent: &Agent) -> Option<String> {
let m = agent.history().first()?;
if m.role != Role::System {
return None;
}
m.contents
.iter()
.find_map(|p| p.as_text())
.map(str::to_string)
}
fn msg(role: Role, text: &str) -> Message {
Message::new(role).with_contents([Part::text(text)])
}
#[tokio::test]
async fn test_simple_builder() {
let agent = builder()
.instruction("You are a test agent.")
.build()
.await
.unwrap();
let history = agent.history();
assert_eq!(history.len(), 1);
assert_eq!(history[0].role, Role::System);
}
#[tokio::test]
async fn test_builder_no_instruction() {
let agent = builder().build().await.unwrap();
assert!(agent.history().is_empty());
assert!(agent.tool_descs.is_empty(), "no sandbox, no system tools");
}
#[tokio::test]
async fn test_builder_sandbox_is_applied() {
let agent = builder()
.sandbox(test_sandbox().await)
.build()
.await
.unwrap();
assert!(agent.tool_descs.iter().any(|t| t.name == "shell"));
let sandbox = agent
.state
.sandbox
.as_ref()
.expect("the supplied sandbox is held");
let result = crate::console::exec(sandbox, ["sh", "-c", "echo ok"], None)
.await
.expect("exec failed");
assert_eq!(result.stdout, "ok\n");
}
#[tokio::test]
async fn test_builder_lists_the_sandbox_abins_as_skills() {
let sandbox = test_sandbox().await;
let with_abin = sandbox
.client()
.create_sandbox(&virtx::SandboxCreateArgs::new("python:3.12-slim").abin("index"))
.await
.expect("making a sandbox with the index abin");
let agent = builder()
.instruction("You are a test agent.")
.sandbox(with_abin.clone())
.build()
.await
.unwrap();
with_abin.remove().await.ok();
sandbox.remove().await.ok();
let text = system_text(&agent).expect("a system message");
assert!(text.starts_with("You are a test agent."), "{text}");
assert!(
text.contains("- `index` at /abin/skills/index/SKILL.md."),
"{text}"
);
}
#[tokio::test]
async fn test_builder_context_manager_is_applied() {
let cm = ContextManager {
max_input_tokens: 10_000,
preserve_recent_turns: 2,
..Default::default()
};
let agent = builder().context_manager(cm).build().await.unwrap();
assert!(agent.context_manager().is_some());
}
#[tokio::test]
async fn test_instruction_seeded_into_history_without_system_message() {
let agent = builder()
.instruction("You are a test agent.")
.history([msg(Role::User, "hello"), msg(Role::Assistant, "hi")])
.build()
.await
.unwrap();
let history = agent.history();
assert_eq!(history.len(), 3);
assert_eq!(
system_text(&agent).as_deref(),
Some("You are a test agent.")
);
assert_eq!(history[1].role, Role::User);
assert_eq!(history[2].role, Role::Assistant);
}
#[tokio::test]
async fn test_existing_system_message_is_not_replaced() {
let agent = builder()
.instruction("spec instruction")
.history([
msg(Role::System, "stored instruction"),
msg(Role::User, "hello"),
])
.build()
.await
.unwrap();
assert_eq!(agent.history().len(), 2);
assert_eq!(system_text(&agent).as_deref(), Some("stored instruction"));
}
}