use crate::built::{BuiltAgent, Discard, Input, RunOutcome};
use crate::error::KitError;
use crate::laws::Laws;
use crate::model::{builtin_catalog, resolve, ModelChoice};
use crate::storage::Storage;
use crate::tool::AsTool;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use toml::Value as Toml;
use troupekit_agent::{
AgentRun, EvalFn, EventSink, InMemoryLedger, Limits, ModelHandle, Persona, SimpleIo,
UsageLedger,
};
use troupekit_core::message::{Message, Role};
use troupekit_core::secret::Secret;
use troupekit_providers::{Catalog, Model, Price, Transport};
use troupekit_tools::{Tool, ToolRegistry, Toolkit};
const MAX_RETRIES: u32 = 32;
pub(crate) struct Prepared {
pub persona: Persona,
pub persona_text: String,
pub tools: Vec<Arc<dyn Tool>>,
pub registry: ToolRegistry,
pub handle: ModelHandle,
pub eval_fns: Vec<(String, EvalFn)>,
pub laws: Laws,
}
const DEFAULT_RETRIES: u32 = 3;
const DEFAULT_ROLE: &str = "An assistant.";
const DEFAULT_GOAL: &str = "Answer the user's request.";
#[derive(Clone)]
pub struct Agent {
name: String,
model: Option<String>,
instructions: Option<String>,
display_name: Option<String>,
role: Option<String>,
goal: Option<String>,
tools: Vec<Arc<dyn Tool>>,
evals: Vec<String>,
eval_fns: Vec<(String, EvalFn)>,
limits: Limits,
max_turns: Option<u32>,
max_tokens: Option<u32>,
pub(crate) storage: Storage,
#[cfg(feature = "knowledge")]
pub(crate) memory: Option<crate::memory::AgentMemory>,
#[cfg(feature = "knowledge")]
pub(crate) knowledge: Option<crate::knowledge::Knowledge>,
catalog: Option<Catalog>,
api_key: Option<Secret>,
api_key_env: Option<String>,
transport: Option<Arc<dyn Transport>>,
model_client: Option<Arc<dyn Model>>,
price: Option<Price>,
events: Option<Arc<dyn EventSink>>,
ledger: Option<Arc<dyn UsageLedger>>,
retries: u32,
law_paths: Vec<PathBuf>,
inline_laws: Vec<String>,
auto_laws: bool,
pub(crate) trace: crate::trace::TraceConfig,
pub(crate) route: crate::route::RouteConfig,
#[cfg(feature = "local")]
pub(crate) local: Option<crate::local::LocalChoice>,
#[cfg(feature = "local")]
pub(crate) download: bool,
}
impl Agent {
pub fn new(name: impl Into<String>) -> Self {
Agent {
name: name.into(),
model: None,
instructions: None,
display_name: None,
role: None,
goal: None,
tools: Vec::new(),
evals: Vec::new(),
eval_fns: Vec::new(),
limits: Limits::default(),
max_turns: None,
max_tokens: None,
storage: Storage::memory(),
#[cfg(feature = "knowledge")]
memory: None,
#[cfg(feature = "knowledge")]
knowledge: None,
catalog: None,
api_key: None,
api_key_env: None,
transport: None,
model_client: None,
price: None,
events: None,
ledger: None,
retries: DEFAULT_RETRIES,
law_paths: Vec::new(),
inline_laws: Vec::new(),
auto_laws: true,
trace: crate::trace::TraceConfig::default(),
route: crate::route::RouteConfig::default(),
#[cfg(feature = "local")]
local: None,
#[cfg(feature = "local")]
download: false,
}
}
pub fn model(mut self, selector: impl Into<String>) -> Self {
self.model = Some(selector.into());
self
}
pub fn instructions(mut self, text: impl Into<String>) -> Self {
self.instructions = Some(text.into());
self
}
pub fn display_name(mut self, text: impl Into<String>) -> Self {
self.display_name = Some(text.into());
self
}
pub fn role(mut self, text: impl Into<String>) -> Self {
self.role = Some(text.into());
self
}
pub fn goal(mut self, text: impl Into<String>) -> Self {
self.goal = Some(text.into());
self
}
pub fn tool(mut self, tool: impl AsTool) -> Self {
self.tools.push(tool.into_arc());
self
}
pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
self.tools.push(tool);
self
}
pub fn tools(mut self, tools: impl IntoIterator<Item = Arc<dyn Tool>>) -> Self {
self.tools.extend(tools);
self
}
pub fn toolkit(mut self, toolkit: Toolkit) -> Self {
self.tools.extend(toolkit.tools().iter().cloned());
self
}
pub fn eval(mut self, call: impl Into<String>) -> Self {
self.evals.push(call.into());
self
}
pub fn evals<S: Into<String>>(mut self, calls: impl IntoIterator<Item = S>) -> Self {
self.evals.extend(calls.into_iter().map(Into::into));
self
}
pub fn eval_fn(mut self, name: impl Into<String>, f: EvalFn) -> Self {
self.eval_fns.push((name.into(), f));
self
}
#[cfg(feature = "knowledge")]
pub fn memory(mut self, memory: crate::memory::AgentMemory) -> Self {
self.memory = Some(memory);
self
}
#[cfg(feature = "knowledge")]
pub fn knowledge(mut self, knowledge: impl Into<crate::knowledge::Knowledge>) -> Self {
self.knowledge = Some(knowledge.into());
self
}
pub fn limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn max_turns(mut self, turns: u32) -> Self {
self.max_turns = Some(turns);
self
}
pub fn max_tokens(mut self, tokens: u32) -> Self {
self.max_tokens = Some(tokens);
self
}
pub fn checkpoints(mut self, storage: Storage) -> Self {
self.storage = storage;
self
}
pub fn catalog(mut self, catalog: Catalog) -> Self {
self.catalog = Some(catalog);
self
}
pub fn api_key(mut self, key: Secret) -> Self {
self.api_key = Some(key);
self
}
pub fn api_key_env(mut self, name: impl Into<String>) -> Self {
self.api_key_env = Some(name.into());
self
}
pub fn transport(mut self, transport: Arc<dyn Transport>) -> Self {
self.transport = Some(transport);
self
}
pub fn model_client(mut self, model: Arc<dyn Model>) -> Self {
self.model_client = Some(model);
self
}
pub fn price(mut self, price: Price) -> Self {
self.price = Some(price);
self
}
pub fn events(mut self, sink: Arc<dyn EventSink>) -> Self {
self.events = Some(sink);
self
}
pub fn ledger(mut self, ledger: Arc<dyn UsageLedger>) -> Self {
self.ledger = Some(ledger);
self
}
pub fn retries(mut self, retries: u32) -> Self {
self.retries = retries;
self
}
pub fn laws(mut self, path: impl AsRef<Path>) -> Self {
self.law_paths.push(path.as_ref().to_path_buf());
self
}
pub fn law(mut self, law: impl Into<String>) -> Self {
self.inline_laws.push(law.into());
self
}
pub fn auto_laws(mut self, on: bool) -> Self {
self.auto_laws = on;
self
}
pub async fn build(self) -> Result<BuiltAgent, KitError> {
let secrets: Vec<Secret> = self.trace_secret().into_iter().collect();
let traced = self.trace.open(&self.name, &self.name, &secrets)?;
match traced {
Some(t) => {
let tracer = t.tracer.clone();
tracer.in_scope(self.build_in(Some(t))).await
}
None => self.build_in(None).await,
}
}
pub(crate) fn trace_secret(&self) -> Option<Secret> {
crate::model::trace_secret(
self.model.as_deref().unwrap_or_default(),
self.api_key.clone(),
self.api_key_env.as_deref(),
)
}
async fn build_in(self, traced: Option<crate::trace::Traced>) -> Result<BuiltAgent, KitError> {
if self.retries > MAX_RETRIES {
return Err(KitError::config(
&self.name,
format!(
"retries must be at most {MAX_RETRIES}, got {}",
self.retries
),
));
}
#[cfg(feature = "local")]
let this = self.load_local(&mut crate::local::Loads::new()).await?;
#[cfg(not(feature = "local"))]
let this = self;
let ledger = this
.ledger
.clone()
.unwrap_or_else(|| Arc::new(InMemoryLedger::default()));
#[cfg(feature = "knowledge")]
let (this, preamble) = {
this.prepare(None, &ledger)?;
crate::memory::attach(this).await?
};
let prepared = this.prepare(None, &ledger)?;
let mut io = SimpleIo::new(prepared.registry);
io.models
.insert(prepared.persona.model.clone(), prepared.handle);
for (eval, f) in &this.eval_fns {
io.evals.register(eval, f.clone())?;
}
io.events = this.events.clone().unwrap_or_else(|| Arc::new(Discard));
io.ledger = ledger;
let probe = vec![Message::text(Role::User, "build check")];
AgentRun::new(&prepared.persona, probe, this.limits.clone(), &io).await?;
let store = this.storage.open().await?;
let built = BuiltAgent::new(
prepared.persona,
io,
this.limits,
store,
this.retries,
prepared.laws,
)
.with_trace(traced);
#[cfg(feature = "knowledge")]
let built = built.with_preamble(preamble);
Ok(built)
}
pub(crate) fn graph_conflict(&self) -> Option<&'static str> {
if self.limits != Limits::default() {
Some("limits; set them on the graph")
} else if !self.law_paths.is_empty() || !self.inline_laws.is_empty() {
Some("laws; set them on the graph")
} else if self.ledger.is_some() {
Some("ledger; set it on the graph")
} else if self.trace.is_on() {
Some("tracing; set it on the graph")
} else if self.has_context() {
Some("memory or knowledge; graphs do not take them in 0.2")
} else {
None
}
}
#[cfg(feature = "knowledge")]
fn check_private_knowledge(&self) -> Result<(), KitError> {
match &self.knowledge {
Some(k)
if self.route.private
&& !k.on_device
&& !(k.embedder.is_none() && self.route.local_only) =>
{
Err(KitError::config(
&self.name,
"a private agent cannot send documents to a cloud embedder: \
use Knowledge::dir(..).on_device_embedder(..)",
))
}
_ => Ok(()),
}
}
#[cfg(not(feature = "knowledge"))]
fn check_private_knowledge(&self) -> Result<(), KitError> {
Ok(())
}
#[cfg(feature = "knowledge")]
fn has_context(&self) -> bool {
self.memory.is_some() || self.knowledge.is_some()
}
#[cfg(not(feature = "knowledge"))]
fn has_context(&self) -> bool {
false
}
pub(crate) fn same_model(&self, other: &Agent) -> bool {
fn same<T: ?Sized>(a: &Option<Arc<T>>, b: &Option<Arc<T>>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
_ => false,
}
}
self.model == other.model
&& same(&self.model_client, &other.model_client)
&& self.price == other.price
&& same(&self.transport, &other.transport)
&& self.api_key == other.api_key
&& self.api_key_env == other.api_key_env
&& self.catalog == other.catalog
&& self.route.same(&other.route)
}
#[cfg(all(feature = "knowledge", feature = "local"))]
pub(crate) async fn knowledge_embedder(
&self,
k: &crate::knowledge::Knowledge,
) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
match &k.local {
Some(choice) => self.local_embedder(choice).await,
None => self.default_embedder(),
}
}
#[cfg(all(feature = "knowledge", not(feature = "local")))]
pub(crate) async fn knowledge_embedder(
&self,
_k: &crate::knowledge::Knowledge,
) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
self.default_embedder()
}
#[cfg(feature = "knowledge")]
pub(crate) fn default_embedder(
&self,
) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
#[cfg(feature = "local")]
if let (true, Some(model)) = (self.route.local_only, &self.route.local_model) {
return crate::local::embedder_of(&self.name, model);
}
crate::model::default_embedder(ModelChoice {
agent: &self.name,
selector: self.model.as_deref().unwrap_or_default(),
catalog: self.catalog.as_ref().unwrap_or_else(|| builtin_catalog()),
client: None,
price: None,
api_key: self.api_key.clone(),
api_key_env: self.api_key_env.as_deref(),
transport: self.transport.clone(),
})
}
pub(crate) fn name(&self) -> &str {
&self.name
}
#[cfg(feature = "local")]
pub(crate) fn selector(&self) -> Option<&str> {
self.model.as_deref()
}
#[cfg(feature = "local")]
pub(crate) fn set_selector(&mut self, selector: String) {
assert!(self.model.is_none(), "an explicit .model(..) is kept");
self.model = Some(selector);
}
#[cfg(feature = "local")]
pub(crate) fn has_client(&self) -> bool {
self.model_client.is_some()
}
#[cfg(feature = "local")]
pub(crate) fn transport_handle(&self) -> Option<Arc<dyn Transport>> {
self.transport.clone()
}
pub(crate) fn prepare(
&self,
model_key: Option<&str>,
ledger: &Arc<dyn UsageLedger>,
) -> Result<Prepared, KitError> {
let name = self.name.as_str();
let Some(instructions) = self.instructions.as_deref() else {
return Err(KitError::config(
name,
"needs instructions: call .instructions(..) or add a /// doc comment",
));
};
let Some(selector) = self.model.as_deref() else {
return Err(KitError::config(
name,
"needs a model: call .model(\"vendor/model\")",
));
};
#[cfg(not(feature = "local"))]
if selector.starts_with("local/") {
return Err(KitError::config(
name,
format!("model `{selector}` needs the `local` feature"),
));
}
self.check_private_knowledge()?;
let mut registry = ToolRegistry::new();
for tool in &self.tools {
registry.register(tool.clone())?;
}
let tool_names: Vec<String> = registry.specs().into_iter().map(|s| s.name).collect();
let (persona, persona_text) =
self.persona(instructions, model_key.unwrap_or(selector), &tool_names)?;
self.route.check_judges(name, &persona)?;
let laws = Laws::check(name, &self.law_paths, &self.inline_laws, self.auto_laws)?;
let catalog = self.catalog.as_ref().unwrap_or_else(|| builtin_catalog());
let handle = self.route.handle(name, ledger, || {
resolve(ModelChoice {
agent: name,
selector,
catalog,
client: self.model_client.clone(),
price: self.price,
api_key: self.api_key.clone(),
api_key_env: self.api_key_env.as_deref(),
transport: self.transport.clone(),
})
})?;
Ok(Prepared {
persona,
persona_text,
tools: self.tools.clone(),
registry,
handle,
eval_fns: self.eval_fns.clone(),
laws,
})
}
pub async fn run(self, input: impl Into<Input>) -> Result<String, KitError> {
self.build().await?.run(input).await
}
pub async fn run_with(self, input: impl Into<Input>) -> Result<RunOutcome, KitError> {
self.build().await?.run_with(input).await
}
fn persona(
&self,
instructions: &str,
selector: &str,
tools: &[String],
) -> Result<(Persona, String), KitError> {
let text_or = |v: &Option<String>, default: &str| {
Toml::String(v.clone().unwrap_or_else(|| default.to_string()))
};
let mut table = toml::Table::new();
table.insert("name".into(), Toml::String(self.name.clone()));
table.insert(
"display_name".into(),
text_or(&self.display_name, &self.name),
);
table.insert("role".into(), text_or(&self.role, DEFAULT_ROLE));
table.insert("goal".into(), text_or(&self.goal, DEFAULT_GOAL));
table.insert(
"instructions".into(),
Toml::String(instructions.to_string()),
);
table.insert("model".into(), Toml::String(selector.to_string()));
let strings =
|items: &[String]| Toml::Array(items.iter().cloned().map(Toml::String).collect());
table.insert("tools".into(), strings(tools));
table.insert("evals".into(), strings(&self.evals));
if let Some(turns) = self.max_turns {
table.insert("max_turns".into(), Toml::Integer(i64::from(turns)));
}
if let Some(tokens) = self.max_tokens {
table.insert("max_tokens".into(), Toml::Integer(i64::from(tokens)));
}
let text = toml::to_string(&table).map_err(|e| {
KitError::config(&self.name, format!("persona does not serialize: {e}"))
})?;
let persona = Persona::parse(&format!("agent:{}", self.name), &text)?;
Ok((persona, text))
}
}
impl fmt::Debug for Agent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tools: Vec<&str> = self.tools.iter().map(|t| t.spec().name.as_str()).collect();
f.debug_struct("Agent")
.field("name", &self.name)
.field("model", &self.model)
.field("tools", &tools)
.field("evals", &self.evals)
.field("storage", &self.storage)
.field("api_key", &self.api_key.as_ref().map(|_| "[redacted]"))
.field("api_key_env", &self.api_key_env)
.field("model_client", &self.model_client.is_some())
.field("retries", &self.retries)
.field("private", &self.route.private)
.field("tier", &self.route.tier)
.field("route", &self.route.has_route())
.field("local_only", &self.route.local_only)
.finish_non_exhaustive()
}
}