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::VendorSpec;
18use troupekit_providers::{Catalog, Model, Price, Transport};
19use troupekit_tools::{Tool, ToolRegistry, Toolkit};
20
21mod from_toml;
22mod start;
23mod stream;
24
25pub use from_toml::MAX_PERSONA_BYTES;
26
27const MAX_RETRIES: u32 = 32;
28
29pub(crate) struct Prepared {
30 pub persona: Persona,
31 pub persona_text: String,
32 pub tools: Vec<Arc<dyn Tool>>,
33 pub registry: ToolRegistry,
34 pub handle: ModelHandle,
35 pub eval_fns: Vec<(String, EvalFn)>,
36 pub laws: Laws,
37}
38const DEFAULT_RETRIES: u32 = 3;
39const DEFAULT_ROLE: &str = "An assistant.";
40const DEFAULT_GOAL: &str = "Answer the user's request.";
41
42#[derive(Clone)]
47pub struct Agent {
48 name: String,
49 model: Option<String>,
50 instructions: Option<String>,
51 display_name: Option<String>,
52 role: Option<String>,
53 goal: Option<String>,
54 tools: Vec<Arc<dyn Tool>>,
55 evals: Vec<String>,
56 eval_fns: Vec<(String, EvalFn)>,
57 limits: Limits,
58 max_turns: Option<u32>,
59 max_tokens: Option<u32>,
60 pub(crate) storage: Storage,
61 #[cfg(feature = "knowledge")]
62 pub(crate) memory: Option<crate::memory::AgentMemory>,
63 #[cfg(feature = "knowledge")]
64 pub(crate) knowledge: Option<crate::knowledge::Knowledge>,
65 catalog: Option<Catalog>,
66 api_key: Option<Secret>,
67 api_key_env: Option<String>,
68 transport: Option<Arc<dyn Transport>>,
69 model_client: Option<Arc<dyn Model>>,
70 price: Option<Price>,
71 events: Option<Arc<dyn EventSink>>,
72 ledger: Option<Arc<dyn UsageLedger>>,
73 retries: u32,
74 law_paths: Vec<PathBuf>,
75 inline_laws: Vec<String>,
76 auto_laws: bool,
77 persona_source: Option<from_toml::PersonaSource>,
78 pub(crate) trace: crate::trace::TraceConfig,
79 pub(crate) route: crate::route::RouteConfig,
80 #[cfg(feature = "local")]
81 pub(crate) local: Option<crate::local::LocalChoice>,
82 #[cfg(feature = "local")]
83 pub(crate) download: bool,
84 #[cfg(feature = "local")]
85 pub(crate) local_settings: troupekit_local::LocalChatSettings,
86}
87
88impl Agent {
89 pub fn new(name: impl Into<String>) -> Self {
93 Agent {
94 name: name.into(),
95 model: None,
96 instructions: None,
97 display_name: None,
98 role: None,
99 goal: None,
100 tools: Vec::new(),
101 evals: Vec::new(),
102 eval_fns: Vec::new(),
103 limits: Limits::default(),
104 max_turns: None,
105 max_tokens: None,
106 storage: Storage::memory(),
107 #[cfg(feature = "knowledge")]
108 memory: None,
109 #[cfg(feature = "knowledge")]
110 knowledge: None,
111 catalog: None,
112 api_key: None,
113 api_key_env: None,
114 transport: None,
115 model_client: None,
116 price: None,
117 events: None,
118 ledger: None,
119 retries: DEFAULT_RETRIES,
120 law_paths: Vec::new(),
121 inline_laws: Vec::new(),
122 auto_laws: true,
123 persona_source: None,
124 trace: crate::trace::TraceConfig::default(),
125 route: crate::route::RouteConfig::default(),
126 #[cfg(feature = "local")]
127 local: None,
128 #[cfg(feature = "local")]
129 download: false,
130 #[cfg(feature = "local")]
131 local_settings: troupekit_local::LocalChatSettings::default(),
132 }
133 }
134
135 pub fn model(mut self, selector: impl Into<String>) -> Self {
139 self.model = Some(selector.into());
140 self
141 }
142
143 pub fn instructions(mut self, text: impl Into<String>) -> Self {
147 self.instructions = Some(text.into());
148 self
149 }
150
151 pub fn display_name(mut self, text: impl Into<String>) -> Self {
155 self.display_name = Some(text.into());
156 self
157 }
158
159 pub fn role(mut self, text: impl Into<String>) -> Self {
163 self.role = Some(text.into());
164 self
165 }
166
167 pub fn goal(mut self, text: impl Into<String>) -> Self {
171 self.goal = Some(text.into());
172 self
173 }
174
175 pub fn tool(mut self, tool: impl AsTool) -> Self {
179 self.tools.push(tool.into_arc());
180 self
181 }
182
183 pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
187 self.tools.push(tool);
188 self
189 }
190
191 pub fn tools(mut self, tools: impl IntoIterator<Item = Arc<dyn Tool>>) -> Self {
195 self.tools.extend(tools);
196 self
197 }
198
199 pub fn toolkit(mut self, toolkit: Toolkit) -> Self {
203 self.tools.extend(toolkit.tools().iter().cloned());
204 self
205 }
206
207 pub fn eval(mut self, call: impl Into<String>) -> Self {
211 self.evals.push(call.into());
212 self
213 }
214
215 pub fn evals<S: Into<String>>(mut self, calls: impl IntoIterator<Item = S>) -> Self {
219 self.evals.extend(calls.into_iter().map(Into::into));
220 self
221 }
222
223 pub fn eval_fn(mut self, name: impl Into<String>, f: EvalFn) -> Self {
227 self.eval_fns.push((name.into(), f));
228 self
229 }
230
231 #[cfg(feature = "knowledge")]
235 pub fn memory(mut self, memory: crate::memory::AgentMemory) -> Self {
236 self.memory = Some(memory);
237 self
238 }
239
240 #[cfg(feature = "knowledge")]
244 pub fn knowledge(mut self, knowledge: impl Into<crate::knowledge::Knowledge>) -> Self {
245 self.knowledge = Some(knowledge.into());
246 self
247 }
248
249 pub fn limits(mut self, limits: Limits) -> Self {
253 self.limits = limits;
254 self
255 }
256
257 pub fn max_turns(mut self, turns: u32) -> Self {
261 self.max_turns = Some(turns);
262 self
263 }
264
265 pub fn max_tokens(mut self, tokens: u32) -> Self {
269 self.max_tokens = Some(tokens);
270 self
271 }
272
273 pub fn checkpoints(mut self, storage: Storage) -> Self {
277 self.storage = storage;
278 self
279 }
280
281 pub fn catalog(mut self, catalog: Catalog) -> Self {
285 self.catalog = Some(catalog);
286 self
287 }
288
289 pub fn api_key(mut self, key: Secret) -> Self {
293 self.api_key = Some(key);
294 self
295 }
296
297 pub fn api_key_env(mut self, name: impl Into<String>) -> Self {
301 self.api_key_env = Some(name.into());
302 self
303 }
304
305 pub fn transport(mut self, transport: Arc<dyn Transport>) -> Self {
309 self.transport = Some(transport);
310 self
311 }
312
313 pub fn model_client(mut self, model: Arc<dyn Model>) -> Self {
317 self.model_client = Some(model);
318 self
319 }
320
321 pub fn price(mut self, price: Price) -> Self {
325 self.price = Some(price);
326 self
327 }
328
329 pub fn events(mut self, sink: Arc<dyn EventSink>) -> Self {
333 self.events = Some(sink);
334 self
335 }
336
337 pub fn ledger(mut self, ledger: Arc<dyn UsageLedger>) -> Self {
341 self.ledger = Some(ledger);
342 self
343 }
344
345 pub fn retries(mut self, retries: u32) -> Self {
349 self.retries = retries;
350 self
351 }
352
353 pub fn laws(mut self, path: impl AsRef<Path>) -> Self {
357 self.law_paths.push(path.as_ref().to_path_buf());
358 self
359 }
360
361 pub fn law(mut self, law: impl Into<String>) -> Self {
365 self.inline_laws.push(law.into());
366 self
367 }
368
369 pub fn auto_laws(mut self, on: bool) -> Self {
373 self.auto_laws = on;
374 self
375 }
376
377 pub async fn build(self) -> Result<BuiltAgent, KitError> {
381 let secrets: Vec<Secret> = self.trace_secret().into_iter().collect();
382 let traced = self.trace.open(&self.name, &self.name, &secrets)?;
383 match traced {
384 Some(t) => {
385 let tracer = t.tracer.clone();
386 tracer.in_scope(self.build_in(Some(t))).await
387 }
388 None => self.build_in(None).await,
389 }
390 }
391
392 pub(crate) fn trace_secret(&self) -> Option<Secret> {
393 crate::model::trace_secret(
394 &self.selector().unwrap_or_default(),
395 self.api_key.clone(),
396 self.api_key_env.as_deref(),
397 )
398 }
399
400 async fn build_in(self, traced: Option<crate::trace::Traced>) -> Result<BuiltAgent, KitError> {
401 if self.retries > MAX_RETRIES {
402 return Err(KitError::config(
403 &self.name,
404 format!(
405 "retries must be at most {MAX_RETRIES}, got {}",
406 self.retries
407 ),
408 ));
409 }
410 #[cfg(feature = "local")]
411 let this = self.load_local(&mut crate::local::Loads::new()).await?;
412 #[cfg(not(feature = "local"))]
413 let this = self;
414 let (store, durable) = this.storage.open().await?;
415 let ledger = this
416 .ledger
417 .clone()
418 .unwrap_or_else(|| Arc::new(InMemoryLedger::default()));
419 let route_ledger = this
420 .ledger
421 .clone()
422 .or(durable)
423 .unwrap_or_else(|| ledger.clone());
424 #[cfg(feature = "knowledge")]
425 let (this, preamble) = {
426 this.prepare(None, &route_ledger)?;
427 crate::memory::attach(this).await?
428 };
429 let prepared = this.prepare(None, &route_ledger)?;
430 let mut io = SimpleIo::new(prepared.registry);
431 io.models
432 .insert(prepared.persona.model.clone(), prepared.handle);
433 for (eval, f) in &this.eval_fns {
434 io.evals.register(eval, f.clone())?;
435 }
436 io.events = this.events.clone().unwrap_or_else(|| Arc::new(Discard));
437 io.ledger = ledger;
438 let probe = vec![Message::text(Role::User, "build check")];
439 AgentRun::new(&prepared.persona, probe, this.limits.clone(), &io).await?;
440 let built = BuiltAgent::new(
441 prepared.persona,
442 io,
443 this.limits,
444 store,
445 this.retries,
446 prepared.laws,
447 )
448 .with_trace(traced);
449 #[cfg(feature = "knowledge")]
450 let built = built.with_preamble(preamble);
451 Ok(built)
452 }
453
454 pub(crate) fn graph_conflict(&self) -> Option<&'static str> {
455 if self.limits != Limits::default() {
456 Some("limits; set them on the graph")
457 } else if !self.law_paths.is_empty() || !self.inline_laws.is_empty() {
458 Some("laws; set them on the graph")
459 } else if self.ledger.is_some() {
460 Some("ledger; set it on the graph")
461 } else if self.trace.is_on() {
462 Some("tracing; set it on the graph")
463 } else if self.has_context() {
464 Some("memory or knowledge; graphs do not take them in 0.2")
465 } else {
466 None
467 }
468 }
469
470 #[cfg(feature = "knowledge")]
471 fn check_private_knowledge(&self) -> Result<(), KitError> {
472 match &self.knowledge {
473 Some(k)
474 if self.route.private
475 && !k.on_device
476 && !(k.embedder.is_none() && self.route.local_only) =>
477 {
478 Err(KitError::config(
479 &self.name,
480 "a private agent cannot send documents to a cloud embedder: \
481 use Knowledge::dir(..).on_device_embedder(..)",
482 ))
483 }
484 _ => Ok(()),
485 }
486 }
487
488 #[cfg(not(feature = "knowledge"))]
489 fn check_private_knowledge(&self) -> Result<(), KitError> {
490 Ok(())
491 }
492
493 fn check_private_tools(&self) -> Result<(), KitError> {
497 if !self.route.private {
498 return Ok(());
499 }
500 let networked = self
501 .tools
502 .iter()
503 .find(|t| t.uses_network() || t.spec().hosted.is_some());
504 match networked {
505 Some(tool) => Err(KitError::config(
506 &self.name,
507 format!(
508 "a private agent cannot use network tool `{}`: drop it or turn private off",
509 tool.spec().name
510 ),
511 )),
512 None => Ok(()),
513 }
514 }
515
516 #[cfg(feature = "knowledge")]
517 fn has_context(&self) -> bool {
518 self.memory.is_some() || self.knowledge.is_some()
519 }
520
521 #[cfg(not(feature = "knowledge"))]
522 fn has_context(&self) -> bool {
523 false
524 }
525
526 pub(crate) fn same_model(&self, other: &Agent) -> bool {
527 fn same<T: ?Sized>(a: &Option<Arc<T>>, b: &Option<Arc<T>>) -> bool {
528 match (a, b) {
529 (None, None) => true,
530 (Some(a), Some(b)) => Arc::ptr_eq(a, b),
531 _ => false,
532 }
533 }
534 self.model == other.model
535 && same(&self.model_client, &other.model_client)
536 && self.price == other.price
537 && same(&self.transport, &other.transport)
538 && self.api_key == other.api_key
539 && self.api_key_env == other.api_key_env
540 && self.catalog == other.catalog
541 && self.persona_source == other.persona_source
542 && self.route.same(&other.route)
543 }
544
545 #[cfg(all(feature = "knowledge", feature = "local"))]
546 pub(crate) async fn knowledge_embedder(
547 &self,
548 k: &crate::knowledge::Knowledge,
549 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
550 match &k.local {
551 Some(choice) => self.local_embedder(choice).await,
552 None => self.default_embedder(),
553 }
554 }
555
556 #[cfg(all(feature = "knowledge", not(feature = "local")))]
557 pub(crate) async fn knowledge_embedder(
558 &self,
559 _k: &crate::knowledge::Knowledge,
560 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
561 self.default_embedder()
562 }
563
564 #[cfg(feature = "knowledge")]
565 pub(crate) fn default_embedder(
566 &self,
567 ) -> Result<Arc<dyn troupekit_context::embed::Embedder>, KitError> {
568 #[cfg(feature = "local")]
569 if let (true, Some(model)) = (self.route.local_only, &self.route.local_model) {
570 return crate::local::embedder_of(&self.name, model);
571 }
572 crate::model::default_embedder(ModelChoice {
573 agent: &self.name,
574 selector: &self
575 .model
576 .clone()
577 .or_else(|| self.toml_selector())
578 .unwrap_or_default(),
579 catalog: self.catalog.as_ref().unwrap_or_else(|| builtin_catalog()),
580 client: None,
581 price: None,
582 api_key: self.api_key.clone(),
583 api_key_env: self.api_key_env.as_deref(),
584 transport: self.transport.clone(),
585 })
586 }
587
588 pub(crate) fn selector(&self) -> Option<String> {
591 self.model.clone().or_else(|| self.toml_selector())
592 }
593
594 pub(crate) fn vendor_spec(&self) -> Option<VendorSpec> {
599 let selector = self.selector()?;
600 let (vendor, _) = selector.split_once('/')?;
601 let catalog = self.catalog.as_ref().unwrap_or_else(|| builtin_catalog());
602 let spec = catalog.vendor(vendor)?.clone();
603 assert_eq!(spec.id, vendor);
604 Some(spec)
605 }
606
607 #[cfg(any(feature = "knowledge", feature = "local"))]
608 pub(crate) fn name(&self) -> &str {
609 &self.name
610 }
611
612 #[cfg(feature = "local")]
613 pub(crate) fn set_selector(&mut self, selector: String) {
614 assert!(self.model.is_none(), "an explicit .model(..) is kept");
615 self.model = Some(selector);
616 }
617
618 #[cfg(feature = "local")]
619 pub(crate) fn has_client(&self) -> bool {
620 self.model_client.is_some()
621 }
622
623 #[cfg(feature = "local")]
624 pub(crate) fn transport_handle(&self) -> Option<Arc<dyn Transport>> {
625 self.transport.clone()
626 }
627
628 pub(crate) fn prepare(
629 &self,
630 model_key: Option<&str>,
631 ledger: &Arc<dyn UsageLedger>,
632 ) -> Result<Prepared, KitError> {
633 let name = self.name.as_str();
634 let toml = self.toml_source()?;
635 if toml.is_none() && self.instructions.is_none() {
636 return Err(KitError::config(
637 name,
638 "needs instructions: call .instructions(..) or add a /// doc comment",
639 ));
640 }
641 if toml.is_none() && self.model.is_none() {
642 return Err(KitError::config(
643 name,
644 "needs a model: call .model(\"vendor/model\")",
645 ));
646 }
647 self.check_private_knowledge()?;
648 self.check_private_tools()?;
649 let mut registry = ToolRegistry::new();
650 for tool in &self.tools {
651 registry.register(tool.clone())?;
652 }
653 let tool_names: Vec<String> = registry.specs().into_iter().map(|s| s.name).collect();
654 let (persona, persona_text, selector) = match toml {
655 Some((source, table)) => self.toml_persona(&source, table, model_key, &tool_names)?,
656 None => {
657 let instructions = self.instructions.as_deref().expect("checked above");
658 let selector = self.model.clone().expect("checked above");
659 let (persona, text) =
660 self.persona(instructions, model_key.unwrap_or(&selector), &tool_names)?;
661 (persona, text, selector)
662 }
663 };
664 #[cfg(not(feature = "local"))]
665 if selector.starts_with("local/") && self.model_client.is_none() {
666 return Err(KitError::config(
667 name,
668 format!("model `{selector}` needs the `local` feature"),
669 ));
670 }
671 self.route.check_judges(name, &persona)?;
672 let laws = Laws::check(name, &self.law_paths, &self.inline_laws, self.auto_laws)?;
673 let catalog = self.catalog.as_ref().unwrap_or_else(|| builtin_catalog());
674 let handle = self.route.handle(name, ledger, || {
675 resolve(ModelChoice {
676 agent: name,
677 selector: &selector,
678 catalog,
679 client: self.model_client.clone(),
680 price: self.price,
681 api_key: self.api_key.clone(),
682 api_key_env: self.api_key_env.as_deref(),
683 transport: self.transport.clone(),
684 })
685 })?;
686 Ok(Prepared {
687 persona,
688 persona_text,
689 tools: self.tools.clone(),
690 registry,
691 handle,
692 eval_fns: self.eval_fns.clone(),
693 laws,
694 })
695 }
696
697 pub async fn run(self, input: impl Into<Input>) -> Result<String, KitError> {
701 self.build().await?.run(input).await
702 }
703
704 pub async fn run_with(self, input: impl Into<Input>) -> Result<RunOutcome, KitError> {
708 self.build().await?.run_with(input).await
709 }
710
711 fn persona(
712 &self,
713 instructions: &str,
714 selector: &str,
715 tools: &[String],
716 ) -> Result<(Persona, String), KitError> {
717 let text_or = |v: &Option<String>, default: &str| {
718 Toml::String(v.clone().unwrap_or_else(|| default.to_string()))
719 };
720 let mut table = toml::Table::new();
721 table.insert("name".into(), Toml::String(self.name.clone()));
722 table.insert(
723 "display_name".into(),
724 text_or(&self.display_name, &self.name),
725 );
726 table.insert("role".into(), text_or(&self.role, DEFAULT_ROLE));
727 table.insert("goal".into(), text_or(&self.goal, DEFAULT_GOAL));
728 table.insert(
729 "instructions".into(),
730 Toml::String(instructions.to_string()),
731 );
732 table.insert("model".into(), Toml::String(selector.to_string()));
733 let strings =
734 |items: &[String]| Toml::Array(items.iter().cloned().map(Toml::String).collect());
735 table.insert("tools".into(), strings(tools));
736 table.insert("evals".into(), strings(&self.evals));
737 if let Some(turns) = self.max_turns {
738 table.insert("max_turns".into(), Toml::Integer(i64::from(turns)));
739 }
740 if let Some(tokens) = self.max_tokens {
741 table.insert("max_tokens".into(), Toml::Integer(i64::from(tokens)));
742 }
743 let text = toml::to_string(&table).map_err(|e| {
744 KitError::config(&self.name, format!("persona does not serialize: {e}"))
745 })?;
746 let persona = Persona::parse(&format!("agent:{}", self.name), &text)?;
747 Ok((persona, text))
748 }
749}
750
751impl fmt::Debug for Agent {
752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753 let tools: Vec<&str> = self.tools.iter().map(|t| t.spec().name.as_str()).collect();
754 f.debug_struct("Agent")
755 .field("name", &self.name)
756 .field("model", &self.model)
757 .field("tools", &tools)
758 .field("evals", &self.evals)
759 .field("storage", &self.storage)
760 .field("api_key", &self.api_key.as_ref().map(|_| "[redacted]"))
761 .field("api_key_env", &self.api_key_env)
762 .field("model_client", &self.model_client.is_some())
763 .field("retries", &self.retries)
764 .field("private", &self.route.private)
765 .field("tier", &self.route.tier)
766 .field("route", &self.route.has_route())
767 .field("local_only", &self.route.local_only)
768 .finish_non_exhaustive()
769 }
770}