1use std::collections::{HashMap, HashSet};
39use std::sync::Arc;
40
41use async_trait::async_trait;
42use serde::{Deserialize, Serialize};
43use tokio::sync::OnceCell;
44use wabot_core::injection::{Container, IsSingleton};
45
46pub mod agents;
47pub mod cache;
48
49pub use agents::{
50 mindset_agent_tools_provider, register_mindset_agent_tools_provider,
51 DynMindsetAgentToolsProvider, MindsetAgentBinding, MindsetAgentTools,
52 MindsetAgentToolsProvider,
53};
54pub use cache::{LoadedMindset, MindsetCache, MindsetCacheConfig};
55
56pub use wabot_feature_tool::{
57 normalize_optional_arguments, parse_tool_arguments, ToolDefinition, ToolError, ToolGate,
58 ToolInvokeFn, ToolInvoker, ToolParameter, ToolSchema,
59};
60
61pub type MindsetTool = ToolSchema;
65pub type MindsetToolParameter = ToolParameter;
67pub type MindsetToolDefinition = ToolDefinition;
69pub type MindsetError = ToolError;
71
72#[derive(Debug, Clone, Default, Serialize, Deserialize)]
74pub struct MindsetIdentity {
75 pub name: String,
76 pub language: String,
77 #[serde(skip_serializing_if = "Option::is_none")]
78 pub personality: Option<String>,
79 #[serde(skip_serializing_if = "Option::is_none")]
80 pub emotions: Option<String>,
81}
82
83impl MindsetIdentity {
84 pub fn new(name: impl Into<String>, language: impl Into<String>) -> Self {
85 Self {
86 name: name.into(),
87 language: language.into(),
88 personality: None,
89 emotions: None,
90 }
91 }
92
93 pub fn with_personality(mut self, personality: impl Into<String>) -> Self {
94 self.personality = Some(personality.into());
95 self
96 }
97
98 pub fn with_emotions(mut self, emotions: impl Into<String>) -> Self {
99 self.emotions = Some(emotions.into());
100 self
101 }
102}
103
104#[derive(Debug, Clone, Default, Serialize, Deserialize)]
111pub struct MindsetDescription {
112 pub identity: MindsetIdentity,
113 pub context: String,
114 pub skills: String,
115 pub limits: String,
116 pub workflow: String,
117}
118
119impl MindsetDescription {
120 pub fn new(identity: MindsetIdentity) -> Self {
121 Self {
122 identity,
123 ..Default::default()
124 }
125 }
126
127 pub fn with_context(mut self, context: impl Into<String>) -> Self {
128 self.context = context.into();
129 self
130 }
131
132 pub fn with_skills(mut self, skills: impl Into<String>) -> Self {
133 self.skills = skills.into();
134 self
135 }
136
137 pub fn with_limits(mut self, limits: impl Into<String>) -> Self {
138 self.limits = limits.into();
139 self
140 }
141
142 pub fn with_workflow(mut self, workflow: impl Into<String>) -> Self {
143 self.workflow = workflow.into();
144 self
145 }
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
153pub enum ModelKind {
154 Llm,
155 VisionLlm,
156 AudioLlm,
157 SpeechToText,
158 TextToSpeech,
159 ImageGen,
160 Embedding,
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
165pub struct MindsetModelRef {
166 #[serde(skip_serializing_if = "Option::is_none")]
167 pub provider: Option<String>,
168 pub model: String,
169}
170
171impl MindsetModelRef {
172 pub fn new(model: impl Into<String>) -> Self {
173 Self {
174 provider: None,
175 model: model.into(),
176 }
177 }
178 pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
179 self.provider = Some(provider.into());
180 self
181 }
182}
183
184#[derive(Debug, Clone, Default)]
186pub struct MindsetModels {
187 map: HashMap<ModelKind, Vec<MindsetModelRef>>,
188}
189
190impl MindsetModels {
191 pub fn new() -> Self {
192 Self::default()
193 }
194 pub fn with(mut self, kind: ModelKind, refs: Vec<MindsetModelRef>) -> Self {
195 self.map.insert(kind, refs);
196 self
197 }
198 pub fn get(&self, kind: ModelKind) -> Option<&[MindsetModelRef]> {
199 self.map.get(&kind).map(|v| v.as_slice())
200 }
201}
202
203#[async_trait]
207pub trait Mindset: Send + Sync {
208 async fn describe(&self) -> MindsetDescription;
211
212 async fn models(&self) -> MindsetModels {
216 MindsetModels::new()
217 }
218
219 fn cache(&self) -> Option<MindsetCacheConfig> {
226 None
227 }
228
229 fn cache_key(&self) -> &'static str {
233 std::any::type_name::<Self>()
234 }
235}
236
237pub struct MindsetOperator {
245 mindset: Arc<dyn Mindset>,
246 container: Container,
247 invoker: ToolInvoker,
248 agent_tools: Option<Arc<dyn MindsetAgentTools>>,
249 cache: Option<Arc<MindsetCache>>,
250 cache_config: Option<MindsetCacheConfig>,
251 loaded: OnceCell<LoadedMindset>,
254}
255
256impl MindsetOperator {
257 pub fn new(container: Container, mindset: Arc<dyn Mindset>) -> Self {
258 let cache_config = mindset.cache();
259 let cache = cache_config.map(|_| {
262 if !container.is_registered::<MindsetCache>() {
263 MindsetCache::register_in(&container);
264 }
265 container.resolve::<MindsetCache>()
266 });
267 Self {
268 mindset,
269 invoker: ToolInvoker::new(container.clone(), Vec::new()),
270 container,
271 agent_tools: None,
272 cache,
273 cache_config,
274 loaded: OnceCell::new(),
275 }
276 }
277
278 pub fn with_module_tools(mut self, tools: Vec<ToolDefinition>) -> Self {
281 let mut all: Vec<ToolDefinition> = self.invoker.all().to_vec();
282 all.extend(tools);
283 self.invoker = ToolInvoker::new(self.container.clone(), all).with_gate(self.gate().clone());
284 self
285 }
286
287 pub fn with_gate(mut self, gate: ToolGate) -> Self {
289 let tools: Vec<ToolDefinition> = self.invoker.all().to_vec();
290 self.invoker = ToolInvoker::new(self.container.clone(), tools).with_gate(gate);
291 self
292 }
293
294 pub fn with_agents(mut self, bindings: Vec<MindsetAgentBinding>) -> Self {
305 if bindings.is_empty() {
306 return self;
307 }
308 let provider = mindset_agent_tools_provider(&self.container).expect(
309 "a mindset declared agents but no agent-tools provider is registered; \
310 call wabot_feature_agent::register_agents(&container) during setup",
311 );
312 let reserved: HashSet<String> = self
315 .invoker
316 .all()
317 .iter()
318 .map(|t| t.name.to_string())
319 .collect();
320 self.agent_tools = Some(provider.create(bindings, &self.container, &reserved));
321 self
322 }
323
324 pub fn mindset(&self) -> &Arc<dyn Mindset> {
325 &self.mindset
326 }
327 pub fn container(&self) -> &Container {
328 &self.container
329 }
330 fn gate(&self) -> &ToolGate {
331 self.invoker.gate()
332 }
333
334 async fn load(&self) -> &LoadedMindset {
338 self.loaded
339 .get_or_init(|| async {
340 let key = self.mindset.cache_key();
341 if let (Some(cache), Some(config)) = (&self.cache, &self.cache_config) {
342 if let Some(hit) = cache.get(key) {
343 if !hit.is_stale(config) {
344 return hit;
345 }
346 }
347 }
348 let (description, models) =
349 tokio::join!(self.mindset.describe(), self.mindset.models());
350 let loaded = LoadedMindset {
351 description: Arc::new(description),
352 models: Arc::new(models),
353 generated_at: std::time::Instant::now(),
354 };
355 if let Some(cache) = &self.cache {
356 cache.set(key, loaded.clone());
357 }
358 loaded
359 })
360 .await
361 }
362
363 pub async fn describe(&self) -> Arc<MindsetDescription> {
365 self.load().await.description.clone()
366 }
367
368 pub async fn identity(&self) -> MindsetIdentity {
369 self.load().await.description.identity.clone()
370 }
371
372 pub async fn models(&self) -> Arc<MindsetModels> {
373 self.load().await.models.clone()
374 }
375
376 pub async fn resolve_models(&self, kind: ModelKind) -> Vec<MindsetModelRef> {
380 let models = self.models().await;
381 if let Some(refs) = models.get(kind) {
382 if !refs.is_empty() {
383 return refs.to_vec();
384 }
385 }
386 if matches!(kind, ModelKind::VisionLlm | ModelKind::AudioLlm) {
387 if let Some(refs) = models.get(ModelKind::Llm) {
388 return refs.to_vec();
389 }
390 }
391 Vec::new()
392 }
393
394 pub async fn system_prompt(&self) -> String {
399 let description = self.describe().await;
400 let identity = &description.identity;
401
402 let language = identity.language.replace('#', " ");
403 let name = identity.name.replace('#', " ");
404 let personality = identity
405 .personality
406 .as_deref()
407 .map(|p| p.replace('#', " "))
408 .filter(|p| !p.is_empty());
409 let context = description.context.replace('#', " ");
410 let skills = description.skills.replace('#', " ");
411 let limits = description.limits.replace('#', " ");
412 let workflow = description.workflow.replace('#', " ");
413 let personality_block = personality
414 .map(|p| format!("## Personality (in your main language)\n{p}"))
415 .unwrap_or_default();
416 format!(
417 "# System Instructions\n\
418 you should act as a assistant.\n\
419 your main language is {language}.\n\
420 your name is {name}.\n\n\
421 {personality_block}\n\n\
422 ## Context (in your main language)\n{context}\n\n\
423 ## Skills (in your main language)\n{skills}\n\n\
424 ## Workflow (in your main language)\n{workflow}\n\n\
425 ## System limitations (in your main language)\n{limits}\n\n\
426 ## Chat memory\n\
427 Next you will receive a chat history, you should use this \
428 information to answer the user."
429 )
430 }
431
432 pub fn tools(&self) -> Result<Vec<MindsetTool>, ToolError> {
438 let mut schemas = self.invoker.schema()?;
439 if let Some(agent_tools) = &self.agent_tools {
440 schemas.extend(agent_tools.schema());
441 }
442 Ok(schemas)
443 }
444
445 pub async fn call_function(&self, name: &str, args_json: &str) -> Result<String, ToolError> {
448 if let Some(agent_tools) = &self.agent_tools {
449 if agent_tools.has(name) {
450 return agent_tools.call(name, args_json).await;
451 }
452 }
453 self.invoker.call(name, args_json).await
454 }
455}
456
457#[cfg(test)]
458mod tests;