### Example: Agent with System Prompt Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent/struct.Agent.html Demonstrates creating an agent with a specific provider and a system prompt. This is a common starting point for many agent applications. ```rust use traitclaw_core::prelude::*; let agent = Agent::with_system(provider, "You are a helpful assistant."); ``` -------------------------------- ### Example Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.Provider.html An example of how to implement the `Provider` trait for a custom LLM provider. ```APIDOC ## Example ```rust use async_trait::async_trait; use traitclaw_core::prelude::*; struct MyProvider; #[async_trait] impl Provider for MyProvider { async fn complete(&self, request: CompletionRequest) -> traitclaw_core::Result { todo!("Send request to LLM API") } async fn stream(&self, request: CompletionRequest) -> traitclaw_core::Result { todo!("Stream response from LLM API") } fn model_info(&self) -> &ModelInfo { todo!("Return model information") } } ``` ``` -------------------------------- ### Example Implementation of Tool Trait Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Tool.html An example demonstrating how to implement the `Tool` trait for a web search functionality. ```APIDOC ## Example ```rust use async_trait::async_trait; use traitclaw_core::prelude::*; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Deserialize, JsonSchema)] struct SearchInput { query: String, } #[derive(Serialize)] struct SearchOutput { results: Vec, } struct WebSearch; #[async_trait] impl Tool for WebSearch { type Input = SearchInput; type Output = SearchOutput; fn name(&self) -> &str { "web_search" } fn description(&self) -> &str { "Search the web" } async fn execute(&self, input: Self::Input) -> traitclaw_core::Result { Ok(SearchOutput { results: vec![format!("Result for: {}", input.query)] }) } } ``` ``` -------------------------------- ### Example Implementation of Provider Trait Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Provider.html This example demonstrates how to implement the `Provider` trait for a custom LLM provider named `MyProvider`. It includes placeholder implementations for the required methods. ```APIDOC ## Example Implementation ```rust use async_trait::async_trait; use traitclaw_core::prelude::*; struct MyProvider; #[async_trait] impl Provider for MyProvider { async fn complete(&self, request: CompletionRequest) -> traitclaw_core::Result { // TODO: Implement logic to send request to LLM API and return CompletionResponse unimplemented!("Send request to LLM API") } async fn stream(&self, request: CompletionRequest) -> traitclaw_core::Result { // TODO: Implement logic to stream response from LLM API unimplemented!("Stream response from LLM API") } fn model_info(&self) -> &ModelInfo { // TODO: Implement logic to return model information unimplemented!("Return model information") } } ``` ``` -------------------------------- ### Agent Start Hook Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.AgentHook.html Called when the agent begins processing input. Override this to perform actions at the start of agent execution. ```rust fn on_agent_start<'life0, 'life1, 'async_trait>( &'life0 self, _input: &'life1 str, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait { // Default implementation async move {}.boxed() } ``` -------------------------------- ### BudgetHint Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Hint.html Example implementation of the Hint trait for BudgetHint, demonstrating how specific hint types can be created. ```APIDOC ### BudgetHint #### `name(&self) -> &'static str` #### `should_trigger(&self, state: &AgentState) -> bool` #### `generate(&self, state: &AgentState) -> HintMessage` #### `injection_point(&self) -> InjectionPoint` ``` -------------------------------- ### Example Tool Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Tool.html Demonstrates implementing the `Tool` trait for a `WebSearch` tool. This includes defining input and output structs, and implementing the required methods. ```rust use async_trait::async_trait; use traitclaw_core::prelude::*; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Deserialize, JsonSchema)] struct SearchInput { query: String, } #[derive(Serialize)] struct SearchOutput { results: Vec, } struct WebSearch; #[async_trait] impl Tool for WebSearch { type Input = SearchInput; type Output = SearchOutput; fn name(&self) -> &str { "web_search" } fn description(&self) -> &str { "Search the web" } async fn execute(&self, input: Self::Input) -> traitclaw_core::Result { Ok(SearchOutput { results: vec![format!("Result for: {}", input.query)] }) } } ``` -------------------------------- ### Minimal AgentBuilder Example Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent_builder/struct.AgentBuilder.html Demonstrates the basic usage of AgentBuilder to create an agent with a provider and a system prompt. Requires a provider to be defined elsewhere. ```rust use traitclaw_core::prelude::*; use traitclaw_core::agent_builder::AgentBuilder; // Minimal agent (provider required): // let agent = AgentBuilder::new() // .provider(my_provider) // .system("You are helpful") // .build()?; ``` -------------------------------- ### Instantiate LlmCompressor Source: https://docs.rs/traitclaw/1.0.0/traitclaw/context_managers/struct.LlmCompressor.html Create a new LlmCompressor instance with a given LLM provider. This is the basic setup for using the compressor. ```rust use traitclaw_core::context_managers::LlmCompressor; let compressor = LlmCompressor::new(provider); ``` -------------------------------- ### RagContextManager prepare Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.ContextManager.html An example implementation of the `prepare` method for `RagContextManager`. It retrieves documents for the last user query and prepends them as a system message. ```rust fn prepare<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, messages: &'life1 mut Vec, _context_window: usize, _state: &'life2 mut AgentState, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, RagContextManager: 'async_trait, ``` -------------------------------- ### on_agent_start Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.AgentHook.html Called when the agent starts processing input. This hook is part of the agent's lifecycle for observability. ```APIDOC ## fn on_agent_start<'life0, 'life1, 'async_trait>( &'life0 self, _input: &'life1 str, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait, ### Description Called when the agent starts processing input. ### Method async fn ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### on_agent_start Hook Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.AgentHook.html Callback executed when the agent begins processing input. Override to perform actions at the start of agent execution. ```rust fn on_agent_start<'life0, 'life1, 'async_trait>( &'life0 self, _input: &'life1 str, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait ``` -------------------------------- ### ReActStrategy Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.AgentStrategy.html Example implementation of AgentStrategy using the ReAct (Reasoning and Acting) approach. ```APIDOC ### impl AgentStrategy for ReActStrategy #### fn execute<'life0, 'life1, 'life2, 'life3, 'async_trait>( &'life0 self, runtime: &'life1 AgentRuntime, input: &'life2 str, session_id: &'life3 str, ) -> Pin> + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait, ReActStrategy: 'async_trait, { // Implementation details for ReAct execution... unimplemented!(); } ``` -------------------------------- ### SystemPromptReminder Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Hint.html Example implementation of the Hint trait for SystemPromptReminder, used for injecting system prompt reminders. ```APIDOC ### SystemPromptReminder #### `name(&self) -> &'static str` #### `should_trigger(&self, state: &AgentState) -> bool` #### `generate(&self, _state: &AgentState) -> HintMessage` #### `injection_point(&self) -> InjectionPoint` ``` -------------------------------- ### GroupedRegistry::new Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.GroupedRegistry.html Creates a new, empty GroupedRegistry. This is the starting point for building a registry. ```APIDOC ## GroupedRegistry::new ### Description Create an empty grouped registry. ### Method ```rust pub fn new() -> GroupedRegistry ``` ### Example ```rust use traitclaw_core::registries::GroupedRegistry; let registry = GroupedRegistry::new(); assert!(registry.is_empty()); ``` ``` -------------------------------- ### ToolCall Example Format Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.ToolCall.html Illustrates the expected format for a tool call, adhering to the OpenAI tool_call specification. This includes the ID, type, and function details with name and arguments. ```json { "id": "call_abc123", "type": "function", "function": { "name": "web_search", "arguments": "{\"query\":\"rust\"}" } } ``` -------------------------------- ### Provider Start Hook Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.AgentHook.html Called before each LLM (provider) call is made. Useful for logging requests or modifying them before they are sent. ```rust fn on_provider_start<'life0, 'life1, 'async_trait>( &'life0 self, _request: &'life1 CompletionRequest, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait { // Default implementation async move {}.boxed() } ``` -------------------------------- ### TruncationHint Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Hint.html Example implementation of the Hint trait for TruncationHint, detailing its behavior for handling conversation truncation. ```APIDOC ### TruncationHint #### `name(&self) -> &'static str` #### `should_trigger(&self, state: &AgentState) -> bool` #### `generate(&self, _state: &AgentState) -> HintMessage` #### `injection_point(&self) -> InjectionPoint` ``` -------------------------------- ### RateLimitGuard::check Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Guard.html An example implementation of the check method for RateLimitGuard. It ignores the action parameter. ```rust fn check(&self, _action: &Action) -> GuardResult; ``` -------------------------------- ### Create an empty GroupedRegistry Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.GroupedRegistry.html Initializes a new, empty GroupedRegistry. Use this to start building your tool registry. ```rust use traitclaw_core::registries::GroupedRegistry; use traitclaw_core::traits::tool_registry::ToolRegistry; let registry = GroupedRegistry::new(); assert!(registry.is_empty()); ``` -------------------------------- ### TeamProgressHint Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Hint.html Example implementation of the Hint trait for TeamProgressHint, showing how to define behavior for team progress-related hints. ```APIDOC ### TeamProgressHint #### `name(&self) -> &'static str` #### `should_trigger(&self, state: &AgentState) -> bool` #### `generate(&self, state: &AgentState) -> HintMessage` #### `injection_point(&self) -> InjectionPoint` ``` -------------------------------- ### Basic unwrap() usage Source: https://docs.rs/traitclaw/1.0.0/traitclaw/error/type.Result.html Demonstrates the basic usage of `unwrap()` to get the value from an `Ok` variant. Panics if the `Result` is an `Err`. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Create Agent with System Prompt Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.Agent.html Use this convenience method to create an agent with a provider and a system prompt. All other settings default to in-memory memory, no tools, and no guards. Use `Agent::builder()` for full customization. ```rust Agent::builder() .provider(provider) .system(system) .build() .unwrap() ``` ```rust use traitclaw_core::prelude::*; let agent = Agent::with_system(provider, "You are a helpful assistant."); ``` -------------------------------- ### Get Error Cause (Deprecated) Source: https://docs.rs/traitclaw/1.0.0/traitclaw/enum.Error.html Deprecated method to get the cause of the error. Replaced by `Error::source` which supports downcasting. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Get Error Description (Deprecated) Source: https://docs.rs/traitclaw/1.0.0/traitclaw/enum.Error.html Deprecated method to get a string description of the error. Use the Display implementation or `to_string()` instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Agent::with_system() Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.Agent.html Create an agent with just a provider and system prompt. This is a convenience shorthand for common agent configurations. ```APIDOC ## Agent::with_system() ### Description Create an agent with just a provider and system prompt. This is a convenience shorthand equivalent to using `Agent::builder()` with only the provider and system set, and then calling `build()`. All other settings use their defaults (in-memory memory, no tools, no guards, etc.). Use `Agent::builder()` for full customization. ### Method ```rust pub fn with_system(provider: impl Provider, system: impl Into) -> Agent ``` ### Example ```rust use traitclaw_core::prelude::*; let agent = Agent::with_system(provider, "You are a helpful assistant."); ``` ### Panics This method cannot panic under normal usage — the internal `build()` call only fails when no provider is set, and `with_system` always provides one. ``` -------------------------------- ### Agent::with_system() Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent/struct.Agent.html Creates an agent with a specified LLM provider and a system prompt. Other settings default to in-memory memory, no tools, and no guards. ```APIDOC ## Agent::with_system() ### Description Create an agent with just a provider and system prompt. This is a convenience shorthand. ### Method `pub fn with_system(provider: impl Provider, system: impl Into) -> Agent` ### Example ```rust use traitclaw_core::prelude::*; let agent = Agent::with_system(provider, "You are a helpful assistant."); ``` ### Panics This method cannot panic under normal usage — the internal `build()` call only fails when no provider is set, and `with_system` always provides one. ``` -------------------------------- ### AgentFactory::spawn_with Source: https://docs.rs/traitclaw/1.0.0/traitclaw/factory/struct.AgentFactory.html Spawns an agent with custom builder configurations, allowing for advanced setup like adding tools or memory. ```APIDOC ## AgentFactory::spawn_with ### Description Spawn an agent with custom builder configuration. Use this escape hatch when you need more than just a system prompt (e.g., adding tools, setting memory, configuring hooks). The closure receives an `AgentBuilder` with the factory’s provider already set. Call builder methods as needed. ### Method `pub fn spawn_with( &self, f: impl FnOnce(AgentBuilder) -> AgentBuilder, ) -> Result` ### Parameters * `f` (impl FnOnce(AgentBuilder) -> AgentBuilder) - A closure that configures the `AgentBuilder`. ### Example ```rust use traitclaw_core::factory::AgentFactory; use traitclaw_core::traits::provider::Provider; let factory = AgentFactory::new(provider); let agent = factory.spawn_with(|b| { b.system("You are a researcher with tools.") .max_iterations(10) })?; ``` ### Errors Returns an error if the builder customization produces an invalid agent configuration. ``` -------------------------------- ### get_context Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.Memory.html Get a value from working memory. ```APIDOC ## get_context ### Description Get a value from working memory. ### Method `get_context` ### Parameters #### Path Parameters - **session_id** (str) - Required - The ID of the session. - **key** (str) - Required - The key of the value to retrieve. ### Response #### Success Response - **Option** - An optional Value object if the key exists, otherwise None. ``` -------------------------------- ### Default AgentConfig Initialization Source: https://docs.rs/traitclaw/1.0.0/traitclaw/config/struct.AgentConfig.html Provides the default configuration for an Agent. This is useful when you need a basic Agent setup without specifying all parameters manually. The default configuration typically sets sensible values for common parameters. ```rust fn default() -> AgentConfig ``` -------------------------------- ### messages Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Memory.html Get conversation messages for a specific session. ```APIDOC ## messages ### Description Get conversation messages for a session. ### Method `messages` ### Parameters #### Path Parameters - **session_id** (str) - Required - The ID of the session to retrieve messages from. ### Response #### Success Response - **Vec** - A vector of Message objects representing the conversation history. ``` -------------------------------- ### on_agent_start Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.AgentHook.html Called when the agent starts processing input. This method is part of the AgentHook trait and is intended for custom logic execution at the beginning of an agent's operation. ```APIDOC ## fn on_agent_start<'life0, 'life1, 'async_trait>( &'life0 self, _input: &'life1 str, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait, Called when the agent starts processing input. ``` -------------------------------- ### ToolRegistry::get_tools Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.DynamicRegistry.html Get all currently enabled tools. ```APIDOC ## ToolRegistry::get_tools ### Description Get all currently enabled tools. ### Method `fn get_tools(&self) -> Vec>` ``` -------------------------------- ### SimpleRegistry::new Source: https://docs.rs/traitclaw/1.0.0/traitclaw/traits/tool_registry/struct.SimpleRegistry.html Creates a new SimpleRegistry instance from a vector of tools. This is the primary way to instantiate a SimpleRegistry. ```APIDOC ## SimpleRegistry::new ### Description Create a registry from an existing tool list. ### Signature ```rust pub fn new(tools: Vec>) -> SimpleRegistry ``` ### Parameters * `tools` - A `Vec` containing `Arc` which represents the tools to be included in the registry. ``` -------------------------------- ### len Source: https://docs.rs/traitclaw/1.0.0/traitclaw/traits/tool_registry/trait.ToolRegistry.html Gets the number of currently enabled tools in the registry. ```APIDOC ## len ### Description Get the number of currently enabled tools. ### Method `fn len(&self) -> usize` ### Parameters None ### Returns - `usize`: The count of enabled tools. ``` -------------------------------- ### Safely pinning a move closure capture using `pin!` Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/type.CompletionStream.html This example shows the recommended approach for handling pinned closures by using the `pin!` macro in the outer function. This ensures the captured variable is pinned before the closure is created, making it safe to move and call the closure multiple times. ```rust use std::pin::pin; use std::task::Context; use std::future::Future; fn move_pinned_closure(mut x: impl Future, cx: &mut Context<'_>) { let mut x = pin!(x); // Create a closure that captures `x: Pin<&mut _>`, which is safe to move. let mut closure = move || { let _ignore = x.as_mut().poll(cx); }; // Call the closure, so the future can assume it has been pinned. closure(); // Move the closure somewhere else. let mut moved = closure; // Calling it again here is fine (except that we might be polling a future that already // returned `Poll::Ready`, but that is a separate problem). moved(); } ``` -------------------------------- ### ToolRegistry::len Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.DynamicRegistry.html Get the number of currently enabled tools. ```APIDOC ## ToolRegistry::len ### Description Get the number of currently enabled tools. ### Method `fn len(&self) -> usize` ``` -------------------------------- ### Get Compression Threshold Source: https://docs.rs/traitclaw/1.0.0/traitclaw/memory/compressed/struct.CompressedMemory.html Retrieves the configured compression threshold for the CompressedMemory. ```rust pub fn threshold(&self) -> usize ``` -------------------------------- ### SimpleRegistry::new Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.SimpleRegistry.html Creates a new SimpleRegistry from an existing list of tools. ```APIDOC ## SimpleRegistry::new ### Description Create a registry from an existing tool list. ### Signature ```rust pub fn new(tools: Vec>) -> SimpleRegistry ``` ``` -------------------------------- ### Implement Any trait Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent/struct.AgentSession.html Provides the `type_id` method to get the `TypeId` of the `AgentSession`. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Create Agent with System Prompt Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent/struct.Agent.html A convenience method to create an agent with a provider and a system prompt. All other settings default to in-memory memory, no tools, and no guards. Use `Agent::builder()` for more control. ```rust Agent::builder() .provider(provider) .system(system) .build() .unwrap() ``` -------------------------------- ### TikTokenCounter Usage Source: https://docs.rs/traitclaw/1.0.0/traitclaw/token_counter/index.html Example of how to use the TikTokenCounter struct for counting tokens in messages. ```APIDOC ## Struct TikTokenCounter Exact token counter using OpenAI-compatible BPE tokenization via tiktoken-rs. ### Usage ```rust use traitclaw_core::token_counter::TikTokenCounter; let counter = TikTokenCounter::for_model("gpt-4o"); let tokens = counter.count_messages(&messages); ``` ### Parameters - `model_name`: The name of the model to use for tokenization (e.g., "gpt-4o"). ### Methods - `count_messages(messages)`: Counts the tokens in a list of messages. ``` -------------------------------- ### fn prepare Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.ContextManager.html Prepare the message list by pruning or compressing if necessary. `context_window` is the model’s maximum token capacity. This method is async to support LLM-powered compression strategies. ```APIDOC ## fn prepare<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, messages: &'life1 mut Vec, context_window: usize, state: &'life2 mut AgentState, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, Self: 'async_trait, ### Description Prepare the message list by pruning or compressing if necessary. `context_window` is the model’s maximum token capacity. This method is async to support LLM-powered compression strategies. ### Parameters - **messages** (*mut Vec*) - The list of messages to prepare. - **context_window** (*usize*) - The model's maximum token capacity. - **state** (*mut AgentState*) - The current agent state. ``` -------------------------------- ### ChainOfThoughtStrategy Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.AgentStrategy.html Example implementation of AgentStrategy using the Chain-of-Thought reasoning approach. ```APIDOC ### impl AgentStrategy for ChainOfThoughtStrategy #### fn execute<'life0, 'life1, 'life2, 'life3, 'async_trait>( &'life0 self, runtime: &'life1 AgentRuntime, input: &'life2 str, session_id: &'life3 str, ) -> Pin> + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait, ChainOfThoughtStrategy: 'async_trait, { // Implementation details for Chain-of-Thought execution... unimplemented!(); } ``` -------------------------------- ### Create an AdaptiveRegistry Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.AdaptiveRegistry.html Initializes an AdaptiveRegistry with a list of tools and a specified model tier. Default tier limits are applied. ```rust use traitclaw_core::registries::AdaptiveRegistry; use traitclaw_core::traits::tool_registry::ToolRegistry; use traitclaw_core::types::model_info::ModelTier; let registry = AdaptiveRegistry::new(vec![], ModelTier::Medium); assert!(registry.is_empty()); ``` -------------------------------- ### Handling File Metadata Operations Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/type.Result.html Shows how to use `and_then` to chain operations that might fail, specifically when retrieving file metadata and modification times. This example uses `Path::metadata` and `metadata.modified()`, handling potential errors like 'NotFound'. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### NoopTracker on_iteration Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/traits/tracker/struct.NoopTracker.html The on_iteration method for NoopTracker does nothing. It is called at the start of each iteration. ```rust fn on_iteration(&self, _state: &mut AgentState) ``` -------------------------------- ### Agent Builder Initialization Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent/struct.Agent.html Use `Agent::builder()` to create a builder for constructing an agent with full customization. This is the recommended approach for complex configurations. ```rust pub fn builder() -> AgentBuilder ``` -------------------------------- ### Get All Enabled Tools Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.ToolRegistry.html Retrieves a vector of all currently enabled tools managed by the registry. ```rust fn get_tools(&self) -> Vec>; ``` -------------------------------- ### DynamicRegistry::with_tools Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.DynamicRegistry.html Creates a registry pre-loaded with tools (all enabled). ```APIDOC ## DynamicRegistry::with_tools ### Description Create a registry pre-loaded with tools (all enabled). ### Method `fn with_tools(tools: Vec>) -> DynamicRegistry` ``` -------------------------------- ### Get the TypeId of a value Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.GroupedRegistry.html Retrieves the `TypeId` of a given value. This is part of the `Any` trait implementation. ```rust let registry = GroupedRegistry::new(); let type_id = registry.type_id(); ``` -------------------------------- ### on_provider_start Hook Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.AgentHook.html Callback executed before each call to an LLM provider. Use to intercept or modify requests. ```rust fn on_provider_start<'life0, 'life1, 'async_trait>( &'life0 self, _request: &'life1 CompletionRequest, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait ``` -------------------------------- ### Get all registered group names Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.GroupedRegistry.html Retrieves a list of names for all groups currently registered in the registry. ```rust let group_names = registry.group_names(); ``` -------------------------------- ### on_provider_start Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.AgentHook.html Called before each LLM (provider) call is made. This allows for pre-computation or modification of the request before it's sent to the provider. ```APIDOC ## fn on_provider_start<'life0, 'life1, 'async_trait>( &'life0 self, _request: &'life1 CompletionRequest, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait, Called before each LLM call is made. ``` -------------------------------- ### Create and spawn agents with AgentFactory Source: https://docs.rs/traitclaw/1.0.0/traitclaw/factory/struct.AgentFactory.html Instantiate an AgentFactory with a provider and then spawn multiple agents, each with a unique system prompt. All spawned agents will share the same underlying provider configuration. ```rust use traitclaw_core::factory::AgentFactory; use traitclaw_core::traits::provider::Provider; let factory = AgentFactory::new(provider); let researcher = factory.spawn("You are a researcher."); let writer = factory.spawn("You are a technical writer."); let reviewer = factory.spawn("You are a code reviewer."); // All three agents share the same provider config (via Arc) ``` -------------------------------- ### Get Length of SimpleRegistry Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.SimpleRegistry.html Returns the number of tools currently in the SimpleRegistry. This is part of the ToolRegistry trait. ```rust fn len(&self) -> usize ``` -------------------------------- ### Get conversation messages for a session Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.InMemoryMemory.html Retrieves all conversation messages associated with a specific session ID. ```rust self.messages(session_id) ``` -------------------------------- ### Create a new InMemoryMemory store Source: https://docs.rs/traitclaw/1.0.0/traitclaw/memory/in_memory/struct.InMemoryMemory.html Instantiate a new, empty in-memory store. This is the default memory backend if none is explicitly configured. ```rust use traitclaw_core::memory::in_memory::InMemoryMemory; let memory = InMemoryMemory::new(); ``` -------------------------------- ### prepare Method Signature Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.ContextManager.html The `prepare` method is responsible for adjusting the message list to fit the context window. It is asynchronous to allow for complex operations like LLM-powered compression. ```rust fn prepare<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, messages: &'life1 mut Vec, context_window: usize, state: &'life2 mut AgentState, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, Self: 'async_trait, ``` -------------------------------- ### Get active group names Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.GroupedRegistry.html Retrieves a list of names for all groups that are currently active in the GroupedRegistry. ```rust let registry = GroupedRegistry::new(); // Assume "group1" is active and "group2" is not let active_names = registry.active_group_names(); ``` -------------------------------- ### LlmCompressor::with_prompt Source: https://docs.rs/traitclaw/1.0.0/traitclaw/context_managers/struct.LlmCompressor.html Sets a custom summarization prompt template for the LlmCompressor. ```APIDOC ## LlmCompressor::with_prompt ### Description Set a custom summarization prompt template. ### Signature ```rust pub fn with_prompt(self, prompt: impl Into) -> LlmCompressor ``` ### Parameters * `prompt` (impl Into) - The custom prompt template string. ``` -------------------------------- ### Get session messages Source: https://docs.rs/traitclaw/1.0.0/traitclaw/memory/in_memory/struct.InMemoryMemory.html Retrieves all conversation messages for a specific session ID. This operation is asynchronous. ```rust async fn get_session_messages(memory: &InMemoryMemory, session_id: &str) -> Result, Error> { memory.messages(session_id).await } ``` -------------------------------- ### Implement Any for Trait Implementations Source: https://docs.rs/traitclaw/1.0.0/traitclaw/enum.HintPriority.html Provides the ability to get the TypeId of a value. This is part of the blanket implementations for Any. ```rust impl Any for T where T: 'static + ?Sized, fn type_id(&self) -> TypeId ``` -------------------------------- ### impl ContextManager for LlmCompressor - prepare Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.LlmCompressor.html Prepares the message list by pruning or compressing if necessary. ```APIDOC ## impl ContextManager for LlmCompressor - prepare ### Description Prepare the message list by pruning or compressing if necessary. ### Signature ```rust fn prepare<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, messages: &'life1 mut Vec, context_window: usize, state: &'life2 mut AgentState, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, LlmCompressor: 'async_trait, ``` ### Parameters * `messages` - A mutable reference to a vector of `Message` objects. * `context_window` - The size of the context window. * `state` - A mutable reference to the `AgentState`. ``` -------------------------------- ### Create and Check Empty DynamicRegistry Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.DynamicRegistry.html Demonstrates creating a new, empty DynamicRegistry and verifying its initial state. This is useful for setting up a registry before adding any tools. ```rust use traitclaw_core::registries::DynamicRegistry; use traitclaw_core::traits::tool_registry::ToolRegistry; let registry = DynamicRegistry::new(); assert!(registry.is_empty()); ``` -------------------------------- ### on_provider_start Source: https://docs.rs/traitclaw/1.0.0/traitclaw/traits/hook/trait.AgentHook.html Called before each LLM call is made. This hook is part of the AgentHook trait. ```APIDOC ## fn on_provider_start<'life0, 'life1, 'async_trait>( &'life0 self, _request: &'life1 CompletionRequest, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait, ### Description Called before each LLM call is made. ``` -------------------------------- ### MctsStrategy Implementation Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.AgentStrategy.html Example implementation of AgentStrategy using the Monte Carlo Tree Search (MCTS) approach. ```APIDOC ### impl AgentStrategy for MctsStrategy #### fn execute<'life0, 'life1, 'life2, 'life3, 'async_trait>( &'life0 self, runtime: &'life1 AgentRuntime, input: &'life2 str, session_id: &'life3 str, ) -> Pin> + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait, MctsStrategy: 'async_trait, { // Implementation details for MCTS execution... unimplemented!(); } ``` -------------------------------- ### Initialize ProgressiveTransformer Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.ProgressiveTransformer.html Create a new ProgressiveTransformer instance. Specify the LLM provider and the maximum length for outputs to be returned unchanged. Outputs exceeding this length will be summarized. ```rust use traitclaw_core::transformers::ProgressiveTransformer; use std::sync::Arc; // let transformer = ProgressiveTransformer::new(provider.clone(), 500) // .with_summary_prompt("Give a one-sentence summary: {output}"); ``` -------------------------------- ### impl AgentHook for Arc::on_provider_start Source: https://docs.rs/traitclaw/1.0.0/traitclaw/traits/hook/trait.AgentHook.html Called when a provider starts. This is a blanket implementation for `Arc` where `T` implements `AgentHook`. ```APIDOC #### fn on_provider_start<'life0, 'life1, 'async_trait>( &'life0 self, request: &'life1 CompletionRequest, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Arc: 'async_trait, Source ``` -------------------------------- ### AgentBuilder::new Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent_builder/struct.AgentBuilder.html Creates a new AgentBuilder with default configuration. ```APIDOC ## AgentBuilder::new ### Description Create a new builder with default configuration. ### Method `new()` ### Returns - `AgentBuilder`: A new instance of the builder. ``` -------------------------------- ### impl AgentHook for Arc::on_agent_start Source: https://docs.rs/traitclaw/1.0.0/traitclaw/traits/hook/trait.AgentHook.html Called when an agent starts. This is a blanket implementation for `Arc` where `T` implements `AgentHook`. ```APIDOC #### fn on_agent_start<'life0, 'life1, 'async_trait>( &'life0 self, input: &'life1 str, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Arc: 'async_trait, Source ``` -------------------------------- ### Create ProgressiveTransformer Instance Source: https://docs.rs/traitclaw/1.0.0/traitclaw/transformers/struct.ProgressiveTransformer.html Instantiate ProgressiveTransformer with an LLM provider and a maximum summary length. Outputs shorter than this length are passed through unchanged. You can optionally override the default summarization prompt. ```rust use traitclaw_core::transformers::ProgressiveTransformer; use std::sync::Arc; // let transformer = ProgressiveTransformer::new(provider.clone(), 500) // .with_summary_prompt("Give a one-sentence summary: {output}"); ``` -------------------------------- ### AgentState::new Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.AgentState.html Creates a new AgentState instance with default values, initializing token usage and context based on the provided model tier and context window size. ```APIDOC ### impl AgentState #### pub fn new(model_tier: ModelTier, context_window: usize) -> AgentState Create a new agent state with defaults. ``` -------------------------------- ### Get Conversation Messages Source: https://docs.rs/traitclaw/1.0.0/traitclaw/traits/memory/trait.Memory.html Retrieves conversation messages for a specific session. This is a required method for the Memory trait. ```rust fn messages<'life0, 'life1, 'async_trait>( &'life0 self, session_id: &'life1 str, ) -> Pin, Error>> + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait; ``` -------------------------------- ### ContextManager::prepare Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.LlmCompressor.html Prepares the message list by pruning or compressing if necessary, using the LlmCompressor's logic. ```APIDOC ## ContextManager::prepare for LlmCompressor ### Description Prepare the message list by pruning or compressing if necessary. ### Arguments * `messages`: A mutable reference to a `Vec` to be prepared. * `context_window`: The `usize` representing the total context window size. * `state`: A mutable reference to an `AgentState`. ### Returns A `Pin + Send + 'async_trait>>>` representing the asynchronous operation. ``` -------------------------------- ### Get Number of Recent Messages Kept Source: https://docs.rs/traitclaw/1.0.0/traitclaw/memory/compressed/struct.CompressedMemory.html Retrieves the number of most recent messages that are preserved uncompressed in the CompressedMemory. ```rust pub fn keep_recent(&self) -> usize ``` -------------------------------- ### Formatter Implementation for Pin Source: https://docs.rs/traitclaw/1.0.0/traitclaw/types/stream/type.CompletionStream.html Details the `fmt` method for `Pin`, allowing it to be formatted using a given formatter. ```APIDOC ## Formatter Implementation for Pin ### Description This implementation allows `Pin` to be formatted. ### Methods #### `fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>` Formats the value using the given formatter. ``` -------------------------------- ### Get Error Source Source: https://docs.rs/traitclaw/1.0.0/traitclaw/enum.Error.html Returns the lower-level source of this error, if any. This is part of the standard Error trait implementation. ```rust fn source(&self) -> Option<&(dyn Error + 'static)> ``` -------------------------------- ### impl RagContextManager::prepare Source: https://docs.rs/traitclaw/1.0.0/traitclaw/trait.ContextManager.html Prepare messages: retrieve docs for last user query, prepend as system message. ```APIDOC ## fn prepare<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, messages: &'life1 mut Vec, _context_window: usize, _state: &'life2 mut AgentState, ) -> Pin + Send + 'async_trait>> where 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, RagContextManager: 'async_trait, ### Description Prepare messages: retrieve docs for last user query, prepend as system message. ### Parameters - **messages** (*mut Vec*) - The list of messages to prepare. - **_context_window** (*usize*) - The model's maximum token capacity (unused in this implementation). - **_state** (*mut AgentState*) - The current agent state (unused in this implementation). ``` -------------------------------- ### DynamicRegistry::new Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.DynamicRegistry.html Creates an empty dynamic registry. ```APIDOC ## DynamicRegistry::new ### Description Create an empty dynamic registry. ### Method `fn new() -> DynamicRegistry` ``` -------------------------------- ### Get the session ID Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent/struct.AgentSession.html Retrieve the unique identifier for the current agent session using the `id` method. ```rust pub fn id(&self) -> &str ``` -------------------------------- ### Create BudgetAwareTruncator Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.BudgetAwareTruncator.html Instantiate a new BudgetAwareTruncator with a maximum character limit and an aggressive threshold. The aggressive threshold determines when to halve the limit to preserve context budget. ```rust use traitclaw_core::transformers::BudgetAwareTruncator; let t = BudgetAwareTruncator::new(1000, 0.8); ``` -------------------------------- ### Run Agent with Input Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.Agent.html Run the agent with user input and return the final output. This method uses the `"default"` session for backward compatibility. For session isolation, use `Agent::session()` or `Agent::session_auto()`. ```rust let output = agent.run("What is the weather today?").await?; ``` -------------------------------- ### GroupedRegistry::new Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.GroupedRegistry.html Creates a new, empty GroupedRegistry. This is the starting point for building a registry with named tool groups. ```APIDOC ## GroupedRegistry::new ### Description Create an empty grouped registry. ### Method `new()` ### Returns - `GroupedRegistry`: An empty grouped registry instance. ``` -------------------------------- ### Create a new session Source: https://docs.rs/traitclaw/1.0.0/traitclaw/memory/in_memory/struct.InMemoryMemory.html Creates a new, unique session ID. This is typically done at the start of a new conversation. ```rust async fn create_new_session(memory: &InMemoryMemory) -> Result { memory.create_session().await } ``` -------------------------------- ### ProgressiveTransformer::with_summary_prompt Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.ProgressiveTransformer.html Overrides the default summarization prompt template. Use `{output}` as the placeholder for the tool output. ```APIDOC ## ProgressiveTransformer::with_summary_prompt ### Description Override the summarization prompt template. ### Parameters #### Path Parameters - **prompt** (impl Into) - Use `{output}` as the placeholder for the tool output. ### Returns ProgressiveTransformer ``` -------------------------------- ### Combining Policies with AND Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.GroupedRegistry.html Creates a new `Policy` that returns `Action::Follow` only if both `self` and `other` policies return `Action::Follow`. ```APIDOC ## fn and ### Description Create a new `Policy` that returns `Action::Follow` only if `self` and `other` return `Action::Follow`. ### Method `and` ### Parameters - `other`: `P` - The other policy to combine with. ### Returns `And` ``` -------------------------------- ### Get Model Information Source: https://docs.rs/traitclaw/1.0.0/traitclaw/retry/struct.RetryProvider.html Retrieves metadata about the model being used by the RetryProvider. This information is static and does not involve retry logic. ```rust fn model_info(&self) -> &ModelInfo ``` -------------------------------- ### Get Tools from SimpleRegistry Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.SimpleRegistry.html Retrieves all currently enabled tools from the SimpleRegistry. This method is part of the ToolRegistry trait implementation. ```rust fn get_tools(&self) -> Vec> ``` -------------------------------- ### Get a value from working memory Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.InMemoryMemory.html Retrieves a specific value from the session's working memory using a key. ```rust self.get_context(session_id, key) ``` -------------------------------- ### AgentBuilder::build Source: https://docs.rs/traitclaw/1.0.0/traitclaw/agent_builder/struct.AgentBuilder.html Builds the agent instance. Returns an error if the provider is not configured. ```APIDOC ## AgentBuilder::build ### Description Build the agent. Returns an error if no provider is configured. ### Method `build(self) -> Result` ### Returns - `Result`: A `Result` containing the built `Agent` on success, or an `Error` if the provider is not configured. ``` -------------------------------- ### Initialize CharApproxCounter and count messages Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.CharApproxCounter.html Create a new CharApproxCounter with a specified characters-per-token ratio and count tokens in a list of messages. Common ratios include 4 for English, 3 for CJK-heavy text, and 2 for code-heavy text. ```rust use traitclaw_core::token_counting::CharApproxCounter; use traitclaw_core::types::message::{Message, MessageRole}; let counter = CharApproxCounter::new(4); let messages = vec![ Message { role: MessageRole::User, content: "Hello world!".to_string(), tool_call_id: None }, ]; let tokens = counter.count(&messages); assert_eq!(tokens, 4); // 12 chars / 4 + 1 = 4 ``` -------------------------------- ### Get tools from active groups only Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.GroupedRegistry.html Retrieves a vector of tools that belong to the currently active groups within the registry. ```rust let registry = GroupedRegistry::new(); // Assume "group1" is active and contains tools let tools = registry.get_tools(); ``` -------------------------------- ### create_session Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/trait.Memory.html Create a new session. ```APIDOC ## create_session ### Description Create a new session. ### Method `create_session` ### Response #### Success Response - **String** - The ID of the newly created session. ``` -------------------------------- ### Create New Session Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.CompressedMemory.html Creates a new, unique session ID for a conversation. This is the first step in starting a new interaction. ```rust fn create_session<'life0, 'async_trait>( &'life0 self, ) -> Pin> + Send + 'async_trait>> where 'life0: 'async_trait, CompressedMemory: 'async_trait, ``` -------------------------------- ### Override Summary Prompt Source: https://docs.rs/traitclaw/1.0.0/traitclaw/struct.ProgressiveTransformer.html Allows customization of the prompt template used for generating summaries. The `{output}` placeholder will be replaced with the actual tool output. ```rust pub fn with_summary_prompt( self, prompt: impl Into, ) -> ProgressiveTransformer ``` -------------------------------- ### Create New AgentState Source: https://docs.rs/traitclaw/1.0.0/traitclaw/prelude/struct.AgentState.html Initializes a new AgentState with default values. Requires the model tier and context window size. ```rust pub fn new(model_tier: ModelTier, context_window: usize) -> AgentState ```