1use crate::built::{BuiltAgent, Discard, Input, RunOutcome};
2use crate::error::KitError;
3use crate::laws::Laws;
4use crate::model::{builtin_catalog, resolve, ModelChoice};
5use crate::storage::Storage;
6use crate::tool::AsTool;
7use std::fmt;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10use toml::Value as Toml;
11use troupekit_agent::{
12 AgentRun, EvalFn, EventSink, InMemoryLedger, Limits, ModelHandle, Persona, SimpleIo,
13 UsageLedger,
14};
15use troupekit_core::message::{Message, Role};
16use troupekit_core::secret::Secret;
17use troupekit_providers::{Catalog, Model, Price, Transport};
18use troupekit_tools::{Tool, ToolRegistry, Toolkit};
19
20const MAX_RETRIES: u32 = 32;
21
22pub(crate) struct Prepared {
23 pub persona: Persona,
24 pub persona_text: String,
25 pub tools: Vec<Arc<dyn Tool>>,
26 pub registry: ToolRegistry,
27 pub handle: ModelHandle,
28 pub eval_fns: Vec<(String, EvalFn)>,
29 pub laws: Laws,
30}
31const DEFAULT_RETRIES: u32 = 3;
32const DEFAULT_ROLE: &str = "An assistant.";
33const DEFAULT_GOAL: &str = "Answer the user's request.";
34
35#[derive(Clone)]
40pub struct Agent {
41 name: String,
42 model: Option<String>,
43 instructions: Option<String>,
44 display_name: Option<String>,
45 role: Option<String>,
46 goal: Option<String>,
47 tools: Vec<Arc<dyn Tool>>,
48 evals: Vec<String>,
49 eval_fns: Vec<(String, EvalFn)>,
50 limits: Limits,
51 max_turns: Option<u32>,
52 max_tokens: Option<u32>,
53 pub(crate) storage: Storage,
54 #[cfg(feature = "knowledge")]
55 pub(crate) memory: Option<crate::memory::AgentMemory>,
56 #[cfg(feature = "knowledge")]
57 pub(crate) knowledge: Option<crate::knowledge::Knowledge>,
58 catalog: Option<Catalog>,
59 api_key: Option<Secret>,
60 api_key_env: Option<String>,
61 transport: Option<Arc<dyn Transport>>,
62 model_client: Option<Arc<dyn Model>>,
63 price: Option<Price>,
64 events: Option<Arc<dyn EventSink>>,
65 ledger: Option<Arc<dyn UsageLedger>>,
66 retries: u32,
67 law_paths: Vec<PathBuf>,
68 inline_laws: Vec<String>,
69 auto_laws: bool,
70 pub(crate) trace: crate::trace::TraceConfig,
71 pub(crate) route: crate::route::RouteConfig,
72 #[cfg(feature = "local")]
73 pub(crate) local: Option<crate::local::LocalChoice>,
74 #[cfg(feature = "local")]
75 pub(crate) download: bool,
76}
77
78impl Agent {
79 pub fn new(name: impl Into<String>) -> Self {
83 Agent {
84 name: name.into(),
85 model: None,
86 instructions: None,
87 display_name: None,
88 role: None,
89 goal: None,
90 tools: Vec::new(),
91 evals: Vec::new(),
92 eval_fns: Vec::new(),
93 limits: Limits::default(),
94 max_turns: None,
95 max_tokens: None,
96 storage: Storage::memory(),
97 #[cfg(feature = "knowledge")]
98 memory: None,
99 #[cfg(feature = "knowledge")]
100 knowledge: None,
101 catalog: None,
102 api_key: None,
103 api_key_env: None,
104 transport: None,
105 model_client: None,
106 price: None,
107 events: None,
108 ledger: None,
109 retries: DEFAULT_RETRIES,
110 law_paths: Vec::new(),
111 inline_laws: Vec::new(),
112 auto_laws: true,
113 trace: crate::trace::TraceConfig::default(),
114 route: crate::route::RouteConfig::default(),
115 #[cfg(feature = "local")]
116 local: None,
117 #[cfg(feature = "local")]
118 download: false,
119 }
120 }
121
122 pub fn model(mut self, selector: impl Into<String>) -> Self {
126 self.model = Some(selector.into());
127 self
128 }
129
130 pub fn instructions(mut self, text: impl Into<String>) -> Self {
134 self.instructions = Some(text.into());
135 self
136 }
137
138 pub fn display_name(mut self, text: impl Into<String>) -> Self {
142 self.display_name = Some(text.into());
143 self
144 }
145
146 pub fn role(mut self, text: impl Into<String>) -> Self {
150 self.role = Some(text.into());
151 self
152 }
153
154 pub fn goal(mut self, text: impl Into<String>) -> Self {
158 self.goal = Some(text.into());
159 self
160 }
161
162 pub fn tool(mut self, tool: impl AsTool) -> Self {
166 self.tools.push(tool.into_arc());
167 self
168 }
169
170 pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
174 self.tools.push(tool);
175 self
176 }
177
178 pub fn tools(mut self, tools: impl IntoIterator<Item = Arc<dyn Tool>>) -> Self {
182 self.tools.extend(tools);
183 self
184 }
185
186 pub fn toolkit(mut self, toolkit: Toolkit) -> Self {
190 self.tools.extend(toolkit.tools().iter().cloned());
191 self
192 }
193
194 pub fn eval(mut self, call: impl Into<String>) -> Self {
198 self.evals.push(call.into());
199 self
200 }
201
202 pub fn evals<S: Into<String>>(mut self, calls: impl IntoIterator<Item = S>) -> Self {
206 self.evals.extend(calls.into_iter().map(Into::into));
207 self
208 }
209
210 pub fn eval_fn(mut self, name: impl Into<String>, f: EvalFn) -> Self {
214 self.eval_fns.push((name.into(), f));
215 self
216 }
217
218 #[cfg(feature = "knowledge")]
222 pub fn memory(mut self, memory: crate::memory::AgentMemory) -> Self {
223 self.memory = Some(memory);
224 self
225 }
226
227 #[cfg(feature = "knowledge")]
231 pub fn knowledge(mut self, knowledge: impl Into<crate::knowledge::Knowledge>) -> Self {
232 self.knowledge = Some(knowledge.into());
233 self
234 }
235
236 pub fn limits(mut self, limits: Limits) -> Self {
240 self.limits = limits;
241 self
242 }
243
244 pub fn max_turns(mut self, turns: u32) -> Self {
248 self.max_turns = Some(turns);
249 self
250 }
251
252 pub fn max_tokens(mut self, tokens: u32) -> Self {
256 self.max_tokens = Some(tokens);
257 self
258 }
259
260 pub fn checkpoints(mut self, storage: Storage) -> Self {
264 self.storage = storage;
265 self
266 }
267
268 pub fn catalog(mut self, catalog: Catalog) -> Self {
272 self.catalog = Some(catalog);
273 self
274 }
275
276 pub fn api_key(mut self, key: Secret) -> Self {
280 self.api_key = Some(key);
281 self
282 }
283
284 pub fn api_key_env(mut self, name: impl Into<String>) -> Self {
288 self.api_key_env = Some(name.into());
289 self
290 }
291
292 pub fn transport(mut self, transport: Arc<dyn Transport>) -> Self {
296 self.transport = Some(transport);
297 self
298 }
299
300 pub fn model_client(mut self, model: Arc<dyn Model>) -> Self {
304 self.model_client = Some(model);
305 self
306 }
307
308 pub fn price(mut self, price: Price) -> Self {
312 self.price = Some(price);
313 self
314 }
315
316 pub fn events(mut self, sink: Arc<dyn EventSink>) -> Self {
320 self.events = Some(sink);
321 self
322 }
323
324 pub fn ledger(mut self, ledger: Arc<dyn UsageLedger>) -> Self {
328 self.ledger = Some(ledger);
329 self
330 }
331
332 pub fn retries(mut self, retries: u32) -> Self {
336 self.retries = retries;
337 self
338 }
339
340 pub fn laws(mut self, path: impl AsRef<Path>) -> Self {
344 self.law_paths.push(path.as_ref().to_path_buf());
345 self
346 }
347
348 pub fn law(mut self, law: impl Into<String>) -> Self {
352 self.inline_laws.push(law.into());
353 self
354 }
355
356 pub fn auto_laws(mut self, on: bool) -> Self {
360 self.auto_laws = on;
361 self
362 }
363
364 pub async fn build(self) -> Result<BuiltAgent, KitError> {
368 let secrets: Vec<Secret> = self.trace_secret().into_iter().collect();
369 let traced = self.trace.open(&self.name, &self.name, &secrets)?;
370 match traced {
371 Some(t) => {
372 let tracer = t.tracer.clone();
373 tracer.in_scope(self.build_in(Some(t))).await
374 }
375 None => self.build_in(None).await,
376 }
377 }
378
379 pub(crate) fn trace_secret(&self) -> Option<Secret> {
380 crate::model::trace_secret(
381 self.model.as_deref().unwrap_or_default(),
382 self.api_key.clone(),
383 self.api_key_env.as_deref(),
384 )
385 }
386
387 async fn build_in(self, traced: Option<crate::trace::Traced>) -> Result<BuiltAgent, KitError> {
388 if self.retries > MAX_RETRIES {
389 return Err(KitError::config(
390 &self.name,
391 format!(
392 "retries must be at most {MAX_RETRIES}, got {}",
393 self.retries
394 ),
395 ));
396 }
397 #[cfg(feature = "local")]
398 let this = self.load_local(&mut crate::local::Loads::new()).await?;
399 #[cfg(not(feature = "local"))]
400 let this = self;
401 let ledger = this
402 .ledger
403 .clone()
404 .unwrap_or_else(|| Arc::new(InMemoryLedger::default()));
405 #[cfg(feature = "knowledge")]
406 let (this, preamble) = {
407 this.prepare(None, &ledger)?;
408 crate::memory::attach(this).await?
409 };
410 let prepared = this.prepare(None, &ledger)?;
411 let mut io = SimpleIo::new(prepared.registry);
412 io.models
413 .insert(prepared.persona.model.clone(), prepared.handle);
414 for (eval, f) in &this.eval_fns {
415 io.evals.register(eval, f.clone())?;
416 }
417 io.events = this.events.clone().unwrap_or_else(|| Arc::new(Discard));
418 io.ledger = ledger;
419 let probe = vec![Message::text(Role::User, "build check")];
420 AgentRun::new(&prepared.persona, probe, this.limits.clone(), &io).await?;
421 let store = this.storage.open().await?;
422 let built = BuiltAgent::new(
423 prepared.persona,
424 io,
425 this.limits,
426 store,
427 this.retries,
428 prepared.laws,
429 )
430 .with_trace(traced);
431 #[cfg(feature = "knowledge")]
432 let built = built.with_preamble(preamble);
433 Ok(built)
434 }
435
436 pub(crate) fn graph_conflict(&self) -> Option<&'static str> {
437 if self.limits != Limits::default() {
438 Some("limits; set them on the graph")
439 } else if !self.law_paths.is_empty() || !self.inline_laws.is_empty() {
440 Some("laws; set them on the graph")
441 } else if self.ledger.is_some() {
442 Some("ledger; set it on the graph")
443 } else if self.trace.is_on() {
444 Some("tracing; set it on the graph")
445 } else if self.has_context() {
446 Some("memory or knowledge; graphs do not take them in 0.2")
447 } else {
448 None
449 }
450 }
451
452 #[cfg(feature = "knowledge")]
453 fn check_private_knowledge(&self) -> Result<(), KitError> {
454 match &self.knowledge {
455 Some(k)
456 if self.route.private
457 && !k.on_device
458 && !(k.embedder.is_none() && self.route.local_only) =>
459 {
460 Err(KitError::config(
461 &self.name,
462 "a private agent cannot send documents to a cloud embedder: \
463 use Knowledge::dir(..).on_device_embedder(..)",
464 ))
465 }
466 _ => Ok(()),
467 }
468 }
469
470 #[cfg(not(feature = "knowledge"))]
471 fn check_private_knowledge(&self) -> Result<(), KitError> {
472 Ok(())
473 }
474
475 #[cfg(feature = "knowledge")]
476 fn has_context(&self) -> bool {
477 self.memory.is_some() || self.knowledge.is_some()
478 }
479
480 #[cfg(not(feature = "knowledge"))]
481 fn has_context(&self) -> bool {
482 false
483 }
484
485 pub(crate) fn same_model(&self, other: &Agent) -> bool {
486 fn same<T: ?Sized>(a: &Option<Arc<T>>, b: &Option<Arc<T>>) -> bool {
487 match (a, b) {
488 (None, None) => true,
489 (Some(a), Some(b)) => Arc::ptr_eq(a, b),
490 _ => false,
491 }
492 }
493 self.model == other.model
494 && same(&self.model_client, &other.model_client)
495 && self.price == other.price
496 && same(&self.transport, &other.transport)
497 && self.api_key == other.api_key
498 && self.api_key_env == other.api_key_env
499 && self.catalog == other.catalog
500 && self.route.same(&other.route)
501 }
502
503 #[cfg(all(feature = "knowledge", feature = "local"))]
504 pub(crate) async fn knowledge_embedder(
505 &self,
506 k: &crate::knowledge::Knowledge,
507 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
508 match &k.local {
509 Some(choice) => self.local_embedder(choice).await,
510 None => self.default_embedder(),
511 }
512 }
513
514 #[cfg(all(feature = "knowledge", not(feature = "local")))]
515 pub(crate) async fn knowledge_embedder(
516 &self,
517 _k: &crate::knowledge::Knowledge,
518 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
519 self.default_embedder()
520 }
521
522 #[cfg(feature = "knowledge")]
523 pub(crate) fn default_embedder(
524 &self,
525 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
526 #[cfg(feature = "local")]
527 if let (true, Some(model)) = (self.route.local_only, &self.route.local_model) {
528 return crate::local::embedder_of(&self.name, model);
529 }
530 crate::model::default_embedder(ModelChoice {
531 agent: &self.name,
532 selector: self.model.as_deref().unwrap_or_default(),
533 catalog: self.catalog.as_ref().unwrap_or_else(|| builtin_catalog()),
534 client: None,
535 price: None,
536 api_key: self.api_key.clone(),
537 api_key_env: self.api_key_env.as_deref(),
538 transport: self.transport.clone(),
539 })
540 }
541
542 pub(crate) fn name(&self) -> &str {
543 &self.name
544 }
545
546 #[cfg(feature = "local")]
547 pub(crate) fn selector(&self) -> Option<&str> {
548 self.model.as_deref()
549 }
550
551 #[cfg(feature = "local")]
552 pub(crate) fn set_selector(&mut self, selector: String) {
553 assert!(self.model.is_none(), "an explicit .model(..) is kept");
554 self.model = Some(selector);
555 }
556
557 #[cfg(feature = "local")]
558 pub(crate) fn has_client(&self) -> bool {
559 self.model_client.is_some()
560 }
561
562 #[cfg(feature = "local")]
563 pub(crate) fn transport_handle(&self) -> Option<Arc<dyn Transport>> {
564 self.transport.clone()
565 }
566
567 pub(crate) fn prepare(
568 &self,
569 model_key: Option<&str>,
570 ledger: &Arc<dyn UsageLedger>,
571 ) -> Result<Prepared, KitError> {
572 let name = self.name.as_str();
573 let Some(instructions) = self.instructions.as_deref() else {
574 return Err(KitError::config(
575 name,
576 "needs instructions: call .instructions(..) or add a /// doc comment",
577 ));
578 };
579 let Some(selector) = self.model.as_deref() else {
580 return Err(KitError::config(
581 name,
582 "needs a model: call .model(\"vendor/model\")",
583 ));
584 };
585 #[cfg(not(feature = "local"))]
586 if selector.starts_with("local/") {
587 return Err(KitError::config(
588 name,
589 format!("model `{selector}` needs the `local` feature"),
590 ));
591 }
592 self.check_private_knowledge()?;
593 let mut registry = ToolRegistry::new();
594 for tool in &self.tools {
595 registry.register(tool.clone())?;
596 }
597 let tool_names: Vec<String> = registry.specs().into_iter().map(|s| s.name).collect();
598 let (persona, persona_text) =
599 self.persona(instructions, model_key.unwrap_or(selector), &tool_names)?;
600 self.route.check_judges(name, &persona)?;
601 let laws = Laws::check(name, &self.law_paths, &self.inline_laws, self.auto_laws)?;
602 let catalog = self.catalog.as_ref().unwrap_or_else(|| builtin_catalog());
603 let handle = self.route.handle(name, ledger, || {
604 resolve(ModelChoice {
605 agent: name,
606 selector,
607 catalog,
608 client: self.model_client.clone(),
609 price: self.price,
610 api_key: self.api_key.clone(),
611 api_key_env: self.api_key_env.as_deref(),
612 transport: self.transport.clone(),
613 })
614 })?;
615 Ok(Prepared {
616 persona,
617 persona_text,
618 tools: self.tools.clone(),
619 registry,
620 handle,
621 eval_fns: self.eval_fns.clone(),
622 laws,
623 })
624 }
625
626 pub async fn run(self, input: impl Into<Input>) -> Result<String, KitError> {
630 self.build().await?.run(input).await
631 }
632
633 pub async fn run_with(self, input: impl Into<Input>) -> Result<RunOutcome, KitError> {
637 self.build().await?.run_with(input).await
638 }
639
640 fn persona(
641 &self,
642 instructions: &str,
643 selector: &str,
644 tools: &[String],
645 ) -> Result<(Persona, String), KitError> {
646 let text_or = |v: &Option<String>, default: &str| {
647 Toml::String(v.clone().unwrap_or_else(|| default.to_string()))
648 };
649 let mut table = toml::Table::new();
650 table.insert("name".into(), Toml::String(self.name.clone()));
651 table.insert(
652 "display_name".into(),
653 text_or(&self.display_name, &self.name),
654 );
655 table.insert("role".into(), text_or(&self.role, DEFAULT_ROLE));
656 table.insert("goal".into(), text_or(&self.goal, DEFAULT_GOAL));
657 table.insert(
658 "instructions".into(),
659 Toml::String(instructions.to_string()),
660 );
661 table.insert("model".into(), Toml::String(selector.to_string()));
662 let strings =
663 |items: &[String]| Toml::Array(items.iter().cloned().map(Toml::String).collect());
664 table.insert("tools".into(), strings(tools));
665 table.insert("evals".into(), strings(&self.evals));
666 if let Some(turns) = self.max_turns {
667 table.insert("max_turns".into(), Toml::Integer(i64::from(turns)));
668 }
669 if let Some(tokens) = self.max_tokens {
670 table.insert("max_tokens".into(), Toml::Integer(i64::from(tokens)));
671 }
672 let text = toml::to_string(&table).map_err(|e| {
673 KitError::config(&self.name, format!("persona does not serialize: {e}"))
674 })?;
675 let persona = Persona::parse(&format!("agent:{}", self.name), &text)?;
676 Ok((persona, text))
677 }
678}
679
680impl fmt::Debug for Agent {
681 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
682 let tools: Vec<&str> = self.tools.iter().map(|t| t.spec().name.as_str()).collect();
683 f.debug_struct("Agent")
684 .field("name", &self.name)
685 .field("model", &self.model)
686 .field("tools", &tools)
687 .field("evals", &self.evals)
688 .field("storage", &self.storage)
689 .field("api_key", &self.api_key.as_ref().map(|_| "[redacted]"))
690 .field("api_key_env", &self.api_key_env)
691 .field("model_client", &self.model_client.is_some())
692 .field("retries", &self.retries)
693 .field("private", &self.route.private)
694 .field("tier", &self.route.tier)
695 .field("route", &self.route.has_route())
696 .field("local_only", &self.route.local_only)
697 .finish_non_exhaustive()
698 }
699}