### Example Usage Source: https://docs.rs/claudius/0.19.0/claudius/struct.Budget.html A complete example demonstrating the creation of a budget, allocation, and consumption of usage. ```APIDOC ## Example ```rust use claudius::{Budget, Usage}; // Create a budget with $10 and realistic token rates let budget = Budget::from_dollars_with_rates( 10.0, // $10 budget 300, // 300 micro-cents per input token 1500, // 1500 micro-cents per output token 150, // 150 micro-cents per cache creation token 75, // 75 micro-cents per cache read token ); // Allocate budget for an operation expecting up to 500 tokens if let Some(mut allocation) = budget.allocate(500) { // Simulate API usage let usage = Usage::new(100, 50); // 100 input, 50 output tokens if allocation.consume_usage(&usage) { println!("Operation completed within budget"); } } ``` ``` -------------------------------- ### PromptTestConfig Examples Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Illustrates how to create and load PromptTestConfig. ```APIDOC ## §Examples ### §Creating a basic configuration: ```rust let config = PromptTestConfig::new("What is the capital of France?") .with_model("claude-haiku-4-5") .expect_contains("Paris"); ``` ### §Loading from file with automatic file references: If `test.yaml` contains: ```yaml name: "Geography Test" prompt: "prompt.yaml" # Content loaded from prompt.yaml system: "system.md" # Content loaded from system.md model: "claude-haiku-4-5" expected_contains: - "capital" ``` Then: ```rust let config = PromptTestConfig::from_file("test.yaml")?; // config.prompt now contains the contents of prompt.yaml // config.system now contains the contents of system.md ``` ``` -------------------------------- ### Budget Usage Example Source: https://docs.rs/claudius/0.19.0/claudius/struct.Budget.html Demonstrates initializing a budget with specific token rates, allocating capacity for an API call, and consuming the actual usage. ```rust use std::sync::Arc; use claudius::{Budget, Usage}; // Create a $5.00 budget with realistic Anthropic API rates let budget = Arc::new(Budget::from_dollars_with_rates( 5.0, // $5.00 total budget 300, // ~$0.0003 per input token 1500, // ~$0.0015 per output token 150, // ~$0.00015 per cache creation token 75, // ~$0.000075 per cache read token )); // Allocate budget for an API call expecting up to 1000 tokens if let Some(mut allocation) = budget.allocate(1000) { println!("Allocated budget for up to {} tokens", allocation.remaining_tokens()); // After making the API call, consume the actual usage let actual_usage = Usage::new(150, 75); // 150 input, 75 output tokens if allocation.consume_usage(&actual_usage) { println!("Successfully consumed budget for actual usage"); } // Unused budget is automatically returned when allocation is dropped } else { println!("Insufficient budget for this operation"); } println!("Remaining budget: ${:.6}", budget.remaining_micro_cents() as f64 / 100_000_000.0); ``` -------------------------------- ### GET /chat/help_text Source: https://docs.rs/claudius/0.19.0/claudius/chat/fn.help_text.html Retrieves the help text string containing descriptions of available commands. ```APIDOC ## GET /chat/help_text ### Description Returns a static string containing help text that describes the available commands for the chat interface. ### Method GET ### Endpoint /chat/help_text ### Response #### Success Response (200) - **body** (string) - The help text describing available commands. #### Response Example "Available commands: help, status, quit" ``` -------------------------------- ### YAML structure for file references Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Example YAML structure demonstrating how to use file references for prompt and system messages. The content of 'prompt.yaml' and 'system.md' will be automatically loaded. ```yaml name: "My Test" prompt: "prompt.yaml" # This file will be loaded system: "system.md" # This file will be loaded model: "claude-haiku-4-5" ``` -------------------------------- ### YAML structure for inheritance and file references Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Example YAML demonstrating inheritance from a base file and referencing a custom prompt file. Note the security restriction on parent directory traversal for inheritance. ```yaml inherits: "../base.yaml" # Inheritance (base.yaml only for parent dirs) name: "Specialized Test" prompt: "custom_prompt.yaml" # File reference ``` -------------------------------- ### Sum Iterator Example Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Illustrates using the `sum` method on an iterator of `Result` values. Similar to `product`, it short-circuits on the first `Err`. This example shows summing integers, returning an error if a negative number is encountered. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); ``` ```rust let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Real-world AI Agent with Budget Management Source: https://docs.rs/claudius/0.19.0/claudius/struct.Budget.html This example demonstrates a simulated AI agent that processes multiple tasks, each with estimated token usage. It uses `Arc` for thread-safe budget management and handles potential budget exhaustion. ```rust use std::sync::Arc; use claudius::{Budget, Usage}; // Simulate an AI agent that processes multiple tasks struct AIAgent { budget: Arc, name: String, } impl AIAgent { fn new(name: String, daily_budget_dollars: f64) -> Self { // Create budget with realistic Anthropic API rates let budget = Arc::new(Budget::from_dollars_with_rates( daily_budget_dollars, 300, // ~$0.0003 per input token 1500, // ~$0.0015 per output token 375, // ~$0.000375 per cache creation token 30, // ~$0.00003 per cache read token )); Self { budget, name } } fn process_task(&self, task_complexity: u32) -> Result { // Estimate tokens based on task complexity let estimated_tokens = task_complexity * 10; let mut allocation = self.budget.allocate(estimated_tokens) .ok_or_else(|| format!( "Agent {} insufficient budget for task (need {} tokens)", self.name, estimated_tokens ))?; // Simulate API call with actual usage let input_tokens = (estimated_tokens * 6) / 10; let output_tokens = (estimated_tokens * 3) / 10; let cache_read_tokens = estimated_tokens / 10; let input_i32 = i32::try_from(input_tokens) .map_err(|_| "Input token count too large for i32".to_string())?; let output_i32 = i32::try_from(output_tokens) .map_err(|_| "Output token count too large for i32".to_string())?; let cache_i32 = i32::try_from(cache_read_tokens) .map_err(|_| "Cache read token count too large for i32".to_string())?; let usage = Usage::new(input_i32, output_i32) .with_cache_read_input_tokens(cache_i32); if allocation.consume_usage(&usage) { Ok(format!("Task completed by {} using {} total tokens", self.name, input_tokens + output_tokens + cache_read_tokens)) } else { Err("Usage calculation error".to_string()) } } fn remaining_budget_dollars(&self) -> f64 { self.budget.remaining_micro_cents() as f64 / 100_000_000.0 } } // Usage example let agent = AIAgent::new("DataAnalyzer".to_string(), 50.0); // $50 daily budget let tasks = vec![5, 10, 15, 8, 12]; // Task complexity scores for (i, &complexity) in tasks.iter().enumerate() { match agent.process_task(complexity) { Ok(result) => { println!("Task {}: {}", i + 1, result); println!(" Remaining budget: ${:.2}", agent.remaining_budget_dollars()); } Err(error) => { println!("Task {}: Failed - {}", i + 1, error); break; } } } ``` -------------------------------- ### Example Usage of MessageCreateTemplate Source: https://docs.rs/claudius/0.19.0/claudius/struct.MessageCreateTemplate.html Demonstrates how to create and apply a MessageCreateTemplate to customize message parameters. Use this to override specific fields like max_tokens or temperature. ```rust let template = MessageCreateTemplate::new() .with_max_tokens(2048) .with_temperature(0.7) .unwrap(); let params = MessageCreateParams::simple("Hello", KnownModel::Claude37SonnetLatest); let params = template.apply(params); assert_eq!(params.max_tokens, 2048); assert_eq!(params.temperature, Some(0.7)); ``` -------------------------------- ### Run Prompt Test with Anthropic Client Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Execute a prompt test using an Anthropic client. This example demonstrates creating a config, running the test, and asserting the API success and printing the response. ```rust let client = Anthropic::new(None)?; let config = PromptTestConfig::new("Hello, world!") .expect_contains("hello") .with_min_length(5); let result = config.run(&client).await?; assert!(result.api_success); println!("Response: {}", result.response); ``` -------------------------------- ### Get ChatConfig Thinking Budget Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatConfig.html Retrieves the configured thinking budget, if it is enabled. ```rust pub fn thinking_budget(&self) -> Option ``` -------------------------------- ### into_ok() - Safely get Ok value (Nightly) Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Returns the contained Ok value without panicking. This is a nightly-only experimental API. ```APIDOC ## into_ok() ### Description Returns the contained `Ok` value without panicking. This is a nightly-only experimental API. It is known to never panic on the result types it is implemented for. ### Method `into_ok()` ### Parameters None ### Request Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Response #### Success Response (T) - Returns the contained `Ok` value. #### Response Example ```rust // If the Result is Ok, returns the contained value. ``` ``` -------------------------------- ### Product Iterator Example Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Demonstrates using the `product` method on an iterator of `Result` values. If any element is an `Err`, the iteration stops and that error is returned. Otherwise, it returns the product of all successful values. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); ``` ```rust let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### Implement ClientLogger for a custom logger Source: https://docs.rs/claudius/0.19.0/claudius/trait.ClientLogger.html An example implementation of ClientLogger that writes API interactions to a file using a Mutex for thread safety. ```rust use claudius::{ClientLogger, Message, MessageStreamEvent}; use std::sync::Mutex; struct FileLogger { file: Mutex, } impl ClientLogger for FileLogger { fn log_response(&self, message: &Message) { let mut file = self.file.lock().unwrap(); writeln!(file, "Response: {}", serde_json::to_string(message).unwrap()).unwrap(); } fn log_stream_event(&self, event: &MessageStreamEvent) { let mut file = self.file.lock().unwrap(); writeln!(file, "Stream event: {}", serde_json::to_string(event).unwrap()).unwrap(); } fn log_stream_message(&self, message: &Message) { let mut file = self.file.lock().unwrap(); writeln!(file, "Stream complete: {}", serde_json::to_string(message).unwrap()).unwrap(); } } ``` -------------------------------- ### Get ChatConfig System Prompt Text Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatConfig.html Retrieves the system prompt as a string slice, if it has been configured. ```rust pub fn system_prompt_text(&self) -> Option<&str> ``` -------------------------------- ### Run a Prompt Test with test_prompt Source: https://docs.rs/claudius/0.19.0/claudius/fn.test_prompt.html Use this helper function for unit tests to run a prompt and get the result. It treats the input as a literal prompt string and handles client creation and configuration. ```rust let result = test_prompt("What is 2 + 2?").await?; assert!(result.api_success); assert!(result.response.len() > 0); ``` -------------------------------- ### Budget Initialization Source: https://docs.rs/claudius/0.19.0/claudius/struct.Budget.html Demonstrates how to create a Budget instance with specific token rates or a flat rate, and from dollar amounts. ```APIDOC ## Budget Initialization This section covers the various ways to initialize a `Budget` object, allowing for fine-grained control over costs associated with different token types or a simplified flat rate. ### `Budget::new_with_rates` Creates a new budget with the specified monetary amount in micro-cents and token rates. - **`budget_micro_cents`** (u64) - Total budget in micro-cents (1/1,000,000 of a cent) - **`input_token_rate_micro_cents`** (u64) - Cost per input token in micro-cents - **`output_token_rate_micro_cents`** (u64) - Cost per output token in micro-cents - **`cache_creation_token_rate_micro_cents`** (u64) - Cost per cache creation token in micro-cents - **`cache_read_token_rate_micro_cents`** (u64) - Cost per cache read token in micro-cents ### `Budget::new_flat_rate` Creates a new budget with a simplified flat rate per token. - **`budget_micro_cents`** (u64) - Total budget in micro-cents - **`token_rate_micro_cents`** (u64) - Cost per token (applies to all token types) ### `Budget::from_dollars_with_rates` Creates a budget from dollars with specified rates per token in micro-cents. ### `Budget::from_dollars_flat_rate` Creates a budget from dollars with a flat rate per token. #### Example ```rust use claudius::Budget; // Create a $10 budget where each token costs 500 micro-cents let budget = Budget::from_dollars_flat_rate(10.0, 500); // This budget can handle up to 20,000,000 tokens (10 * 100,000,000 / 500) assert!(budget.allocate(1000).is_some()); ``` ### `Budget::new` (Deprecated) Deprecated: Use `new_with_rates` or `new_flat_rate` instead. Legacy constructor for backward compatibility - creates a token-based budget. This converts tokens to micro-cents using a default rate. ``` -------------------------------- ### Example Usage of ToolParam with Strict Mode Source: https://docs.rs/claudius/0.19.0/claudius/struct.ToolParam.html Demonstrates creating a ToolParam for a weather tool, specifying its schema and enabling strict validation. Ensure 'structured-outputs-2025-11-13' header is used for strict mode. ```rust use serde_json::json; use claudius::ToolParam; let tool = ToolParam::new( "get_weather".to_string(), json!({ "type": "object", "properties": { "location": { "type": "string" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"], "additionalProperties": false }) ) .with_strict(true); ``` -------------------------------- ### Get TypeId of MessageStopEvent Source: https://docs.rs/claudius/0.19.0/claudius/struct.MessageStopEvent.html Gets the TypeId of the MessageStopEvent. This is part of the Any trait implementation for generic types. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Get Error Source Source: https://docs.rs/claudius/0.19.0/claudius/enum.Error.html Returns the lower-level source of this error, if any. ```rust fn source(&self) -> Option<&(dyn Error + 'static)> ``` -------------------------------- ### Anthropic Client Initialization Source: https://docs.rs/claudius/0.19.0/claudius/struct.Anthropic.html Demonstrates how to create a new Anthropic client, with options for providing an API key and configuring the base URL and timeout. ```APIDOC ## Anthropic Client Initialization ### Description Initializes a new Anthropic client. The API key can be provided directly or read from environment variables. The base URL can also be configured via environment variables or explicitly set. ### Method `Anthropic::new(api_key: Option) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Using API key directly let client = Anthropic::new(Some("my-api-key".to_string()))?; // Reading API key from environment variable let client = Anthropic::new(None)?; ``` ### Response #### Success Response (200) An initialized `Anthropic` client instance. #### Response Example ```rust // Successful client creation let client: Anthropic = Anthropic::new(Some("api-key".to_string()))?; ``` ``` -------------------------------- ### GET /chat/session_management Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Methods for managing the state and configuration of a ChatSession. ```APIDOC ## GET /chat/session_management ### Description Utility methods to manage conversation history, configuration, and transcript persistence. ### Methods - **clear()**: Clears the conversation history. - **message_count()**: Returns the number of messages in the conversation. - **save_transcript_to(path)**: Saves the transcript to the specified path. - **load_transcript_from(path)**: Loads a transcript from disk, replacing the current conversation history. - **stats()**: Returns the current session statistics snapshot. ``` -------------------------------- ### SystemPrompt Implementations Source: https://docs.rs/claudius/0.19.0/claudius/enum.SystemPrompt.html Provides methods for creating SystemPrompt instances from strings and text blocks, along with trait implementations for common operations. ```APIDOC ## Implementations ### impl SystemPrompt #### pub fn from_string(content: String) -> Self Create a new SystemPrompt from a string. #### pub fn from_blocks(blocks: Vec) -> Self Create a new SystemPrompt from text blocks. ``` ```APIDOC ### impl From<&str> for SystemPrompt #### fn from(content: &str) -> Self Converts to this type from the input type. ### impl From for SystemPrompt #### fn from(content: String) -> Self Converts to this type from the input type. ### impl From> for SystemPrompt #### fn from(blocks: Vec) -> Self Converts to this type from the input type. ``` -------------------------------- ### Get Status Code Source: https://docs.rs/claudius/0.19.0/claudius/enum.Error.html Returns the status code associated with this error, if any. ```rust pub fn status_code(&self) -> Option ``` -------------------------------- ### Get Request ID Source: https://docs.rs/claudius/0.19.0/claudius/enum.Error.html Returns the request ID associated with this error, if any. ```rust pub fn request_id(&self) -> Option<&str> ``` -------------------------------- ### Get ChatConfig Model Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatConfig.html Retrieves the currently configured language model. ```rust pub fn model(&self) -> Model ``` -------------------------------- ### Create Basic PromptTestConfig Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Instantiates a PromptTestConfig with a prompt and sets the model and expected content. Use this for simple test cases. ```rust let config = PromptTestConfig::new("What is the capital of France?") .with_model("claude-haiku-4-5") .expect_contains("Paris"); ``` -------------------------------- ### Create File Source: https://docs.rs/claudius/0.19.0/claudius/trait.Agent.html Creates a new file with specified content. Returns 'success' on creation or an error if the file exists, no filesystem is available, or permissions are denied. ```rust fn create<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, path: &'life1 str, file_text: &'life2 str, ) -> Pin> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, ``` ```rust let result = agent.create("new_file.txt", "Hello, world!").await?; assert_eq!(result, "success"); ``` -------------------------------- ### Get Domain from WebSearchResultBlock URL Source: https://docs.rs/claudius/0.19.0/claudius/struct.WebSearchResultBlock.html Extracts the domain (host) from the URL of a WebSearchResultBlock. ```rust pub fn domain(&self) -> Option ``` -------------------------------- ### ConfigAgent Initialization Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ConfigAgent.html How to instantiate a new ConfigAgent using a ChatConfig object. ```APIDOC ## ConfigAgent::new ### Description Creates a new chat agent instance from a provided ChatConfig. ### Parameters #### Request Body - **config** (ChatConfig) - Required - The configuration object defining agent behavior. ``` -------------------------------- ### Get Default MessageStopEvent Source: https://docs.rs/claudius/0.19.0/claudius/struct.MessageStopEvent.html Returns the default value for MessageStopEvent. This is part of the Default trait. ```rust fn default() -> Self ``` -------------------------------- ### Create a new PromptTestConfig Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Initializes a new PromptTestConfig with a given prompt string. Use this for simple, single-turn prompt tests. ```rust let config = PromptTestConfig::new("What is the capital of France?"); assert_eq!(config.prompt, Some("What is the capital of France?".to_string())); ``` -------------------------------- ### Get ChatConfig Stop Sequences Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatConfig.html Retrieves a slice of the configured stop sequences, if any are set. ```rust pub fn stop_sequences(&self) -> &[String] ``` -------------------------------- ### Create Budget with Flat Rate per Token Source: https://docs.rs/claudius/0.19.0/claudius/struct.Budget.html Use this to create a budget with a single rate applied to all token types. It shows how to set a budget in dollars and a flat rate per token in micro-cents. ```rust // Create a $10 budget where each token costs 500 micro-cents let budget = Budget::from_dollars_flat_rate(10.0, 500); // This budget can handle up to 20,000,000 tokens (10 * 100,000,000 / 500) assert!(budget.allocate(1000).is_some()); ``` -------------------------------- ### Get Chat Configuration Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Returns an immutable reference to the chat session's configuration. ```rust pub fn config(&self) -> &ChatConfig ``` -------------------------------- ### Load PromptTestConfig from File with File References Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Loads a PromptTestConfig from a YAML file, automatically resolving content from 'prompt.yaml' and 'system.md' if specified. Ensure these files exist relative to the configuration file. ```yaml name: "Geography Test" prompt: "prompt.yaml" # Content loaded from prompt.yaml system: "system.md" # Content loaded from system.md model: "claude-haiku-4-5" expected_contains: - "capital" ``` ```rust let config = PromptTestConfig::from_file("test.yaml")?; // config.prompt now contains the contents of prompt.yaml // config.system now contains the contents of system.md ``` -------------------------------- ### Get Message Count Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Returns the total number of messages currently in the conversation history. ```rust pub fn message_count(&self) -> usize ``` -------------------------------- ### PromptTestConfig::new Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Constructor for creating a new PromptTestConfig with a prompt. ```APIDOC ## impl PromptTestConfig ### pub fn new(prompt: impl Into) -> Self Create a new prompt test configuration with just a prompt. ``` -------------------------------- ### FileSystem::create Source: https://docs.rs/claudius/0.19.0/claudius/trait.FileSystem.html Creates a new file at the specified path with the provided content, ensuring it does not already exist. ```APIDOC ## POST /create ### Description Creates a file within the filesystem path. This implementation uses atomic file creation semantics to prevent accidental overwrites. ### Method POST ### Parameters #### Request Body - **path** (str) - Required - The path where the file should be created - **file_text** (str) - Required - The content to write to the new file ### Response #### Success Response (200) - **result** (String) - Success message or file status #### Errors - Returns std::io::ErrorKind::AlreadyExists if the file already exists. - Returns other I/O errors if file creation fails. ``` -------------------------------- ### Get ToolBash20241022 Callback Source: https://docs.rs/claudius/0.19.0/claudius/struct.ToolBash20241022.html Returns the callback implementation for the ToolBash20241022 tool. This is part of the Tool trait. ```rust fn callback(&self) -> Box + '_> ``` -------------------------------- ### POST /create Source: https://docs.rs/claudius/0.19.0/claudius/trait.Agent.html Creates a new file at the specified path with the provided content. Returns a success message if the operation completes, or an error if the file exists or I/O fails. ```APIDOC ## POST /create ### Description Creates a file or returns an error if it already exists. This is a convenience method that delegates to the underlying filesystem. ### Parameters #### Request Body - **path** (str) - Required - The path where the file should be created - **file_text** (str) - Required - The content to write to the new file ### Response #### Success Response (200) - **result** (String) - Returns "success" on successful file creation. #### Errors - Returns an error if no filesystem is available, the file already exists, permission is denied, or other I/O errors occur. ``` -------------------------------- ### Get ToolBash20241022 Name Source: https://docs.rs/claudius/0.19.0/claudius/struct.ToolBash20241022.html Returns the name of the tool, which is 'bash' for ToolBash20241022. This is part of the Tool trait. ```rust fn name(&self) -> String ``` -------------------------------- ### PromptTestConfig Builder Methods Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Methods for configuring a prompt test instance using a fluent builder pattern. ```APIDOC ## PromptTestConfig Builder Methods ### Description Methods to configure test parameters such as system prompts, model selection, token limits, and expectations. ### Methods - **new(prompt: String)**: Create a new test with a single prompt. - **new_conversation(messages: Vec)**: Create a new multi-turn conversation test. - **with_name(name: String)**: Set the test name. - **with_system(system: String)**: Set the system prompt. - **with_model(model: String)**: Set the model to use. - **with_max_tokens(max_tokens: u32)**: Set the maximum tokens. - **with_temperature(temperature: f32)**: Set the temperature. - **expect_contains(content: String)**: Add expected content. - **expect_not_contains(content: String)**: Add content that should NOT appear. - **with_min_length(min_length: usize)**: Set minimum response length. - **with_max_length(max_length: usize)**: Set maximum response length. - **with_tool(tool: ToolUnionParam)**: Add a tool. - **with_tool_choice(tool_choice: ToolChoice)**: Set tool choice. - **expect_tool_call(tool_name: String)**: Expect a specific tool call. - **expect_error()**: Expect an error. - **expect_error_message(message: String)**: Expect a specific error message. - **with_output_format(output_format: OutputFormat)**: Set structured output format (JSON schema). ``` -------------------------------- ### Get Owned Type of MessageStopEvent Source: https://docs.rs/claudius/0.19.0/claudius/struct.MessageStopEvent.html Defines the owned type for MessageStopEvent, which is itself. Part of the ToOwned trait. ```rust type Owned = T ``` -------------------------------- ### Get Owned Version of a Type Source: https://docs.rs/claudius/0.19.0/claudius/struct.ContentBlockStopEvent.html The resulting type after obtaining ownership. This is part of the ToOwned trait. ```rust type Owned = T ``` -------------------------------- ### Get Error Description (Deprecated) Source: https://docs.rs/claudius/0.19.0/claudius/enum.Error.html Deprecated: use the Display impl or to_string() for error description. ```rust fn description(&self) -> &str ``` -------------------------------- ### Create and Allocate Budget with Specific Rates Source: https://docs.rs/claudius/0.19.0/claudius/struct.Budget.html Use this to create a budget with custom rates for input, output, cache creation, and cache read tokens. It demonstrates allocating budget for an operation and consuming usage. ```rust use claudius::{Budget, Usage}; // Create a budget with $10 and realistic token rates let budget = Budget::from_dollars_with_rates( 10.0, // $10 budget 300, // 300 micro-cents per input token 1500, // 1500 micro-cents per output token 150, // 150 micro-cents per cache creation token 75, // 75 micro-cents per cache read token ); // Allocate budget for an operation expecting up to 500 tokens if let Some(mut allocation) = budget.allocate(500) { // Simulate API usage let usage = Usage::new(100, 50); // 100 input, 50 output tokens if allocation.consume_usage(&usage) { println!("Operation completed within budget"); } } ``` -------------------------------- ### Get ChatConfig Max Tokens Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatConfig.html Retrieves the configured maximum number of tokens per response. ```rust pub fn max_tokens(&self) -> u32 ``` -------------------------------- ### Create New ServerToolUsage Source: https://docs.rs/claudius/0.19.0/claudius/struct.ServerToolUsage.html Creates a new ServerToolUsage instance. Initialize with the count of web search requests. ```rust pub fn new(web_search_requests: i32) -> Self ``` -------------------------------- ### Get Mutable Message Template Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Returns a mutable reference to the message template, allowing modifications. ```rust pub fn template_mut(&mut self) -> &mut MessageCreateTemplate ``` -------------------------------- ### Create Enabled Thinking Configuration Source: https://docs.rs/claudius/0.19.0/claudius/enum.ThinkingConfig.html Creates a new enabled thinking configuration with the specified budget tokens. Budget tokens must be greater than or equal to 1024. Use this to enable thinking with a token limit. ```rust pub fn enabled(budget_tokens: u32) -> Self ``` -------------------------------- ### Get Message Template Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Returns an immutable reference to the message template used for API requests. ```rust pub fn template(&self) -> &MessageCreateTemplate ``` -------------------------------- ### ToolBash20241022 Configuration Source: https://docs.rs/claudius/0.19.0/claudius/struct.ToolBash20241022.html Details regarding the structure and fields required to initialize the Bash tool. ```APIDOC ## ToolBash20241022 Structure ### Description Represents the configuration parameters for the Bash tool (version 20241022), enabling the AI to execute bash commands. ### Fields - **name** (String) - Required - The name of the tool. Must be set to "bash". - **cache_control** (Option) - Optional - Defines a cache control breakpoint. If provided, instructs the API not to cache this tool or its results. ### Methods - **new() -> Self** - Creates a new Bash tool parameter object with default settings. - **with_ephemeral_cache_control(self) -> Self** - Sets the cache control to ephemeral for this tool instance. ``` -------------------------------- ### Get page count for CitationPageLocation Source: https://docs.rs/claudius/0.19.0/claudius/struct.CitationPageLocation.html Returns the number of pages in the citation span, calculated as an inclusive range. ```rust pub fn page_count(&self) -> i32 ``` -------------------------------- ### POST /to_file Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Saves the current prompt test configuration to a YAML file. ```APIDOC ## POST /to_file ### Description Serializes and saves the prompt test configuration to a specified YAML file path. ### Method POST ### Endpoint /to_file ### Parameters #### Path Parameters - **path** (P: AsRef) - Required - The file system path where the configuration should be saved. ### Errors - Returns an error if the configuration file cannot be written or if serialization fails. ``` -------------------------------- ### Get Session Statistics Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Returns a snapshot of the current session statistics, such as message counts and token usage. ```rust pub fn stats(&self) -> SessionStats ``` -------------------------------- ### Loading Configuration from File Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Methods for loading test configurations from YAML files, supporting inheritance and file references. ```APIDOC ## Loading Configuration from File ### Description Load a prompt test configuration from a YAML file. Supports configuration inheritance and automatic loading of external files for prompts and system instructions. ### Methods - **from_file

(path: P)**: Load configuration from a YAML file. - **from_file_with_base_dir

(path: P, base_dir: Option<&Path>)**: Load configuration with a specific base directory override. ### Features - **Configuration Inheritance**: Supports `inherits` field for hierarchy. - **File Reference Resolution**: Automatically loads files ending in `prompt.yaml` or `system.md` relative to the config file. ### Errors - Returns error if file is unreadable, YAML is invalid, or inheritance/reference paths are unsafe. ``` -------------------------------- ### Get Mutable Chat Configuration Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Returns a mutable reference to the chat session's configuration, allowing modifications. ```rust pub fn config_mut(&mut self) -> &mut ChatConfig ``` -------------------------------- ### Providing a Default Value with `unwrap_or` Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Demonstrates how to get the `Ok` value or a default value if the `Result` is `Err` using `unwrap_or`. ```APIDOC ## `unwrap_or` ### Description Returns the contained `Ok` value or a provided default. Arguments passed to `unwrap_or` are eagerly evaluated. ### Method `unwrap_or` ### Parameters - `default` (T) - The default value to return if `self` is `Err`. ### Request Example ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` ### Response #### Success Value (T) - Returns the `Ok` value if `self` is `Ok`. #### Default Value (T) - Returns the `default` value if `self` is `Err`. ``` -------------------------------- ### Policy And Implementation Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Combines two policies, requiring both to return `Action::Follow` for the combined policy to follow. ```rust fn and(self, other: P) -> And where T: Policy, P: Policy, ``` -------------------------------- ### Check if CitationPageLocation is single page Source: https://docs.rs/claudius/0.19.0/claudius/struct.CitationPageLocation.html Returns true if the citation is for only a single page, indicating start and end page numbers are the same. ```rust pub fn is_single_page(&self) -> bool ``` -------------------------------- ### Implement CloneToUninit (Nightly) Source: https://docs.rs/claudius/0.19.0/claudius/enum.Content.html An experimental nightly-only API for performing copy-assignment from self to an uninitialized destination. Use with caution. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Configure Anthropic Client Base URL Source: https://docs.rs/claudius/0.19.0/claudius/struct.Anthropic.html Demonstrates setting custom base URLs for different API providers like Anthropic or Minimax. ```rust // For Anthropic's API (default) let client = Anthropic::new(Some("api-key".to_string()))? .with_base_url("https://api.anthropic.com".to_string()); // For Minimax (international) let client = Anthropic::new(Some("api-key".to_string()))? .with_base_url("https://api.minimax.io/anthropic".to_string()); // For Minimax (China) let client = Anthropic::new(Some("api-key".to_string()))? .with_base_url("https://api.minimaxi.com/anthropic".to_string()); ``` -------------------------------- ### into_err() - Safely get Err value (Nightly) Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Returns the contained Err value without panicking. This is a nightly-only experimental API. ```APIDOC ## into_err() ### Description Returns the contained `Err` value without panicking. This is a nightly-only experimental API. It is known to never panic on the result types it is implemented for. ### Method `into_err()` ### Parameters None ### Request Example ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` ### Response #### Success Response (E) - Returns the contained `Err` value. #### Response Example ```rust // If the Result is Err, returns the contained error value. ``` ``` -------------------------------- ### Handle Default Tool Use Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ConfigAgent.html Default implementation for handling tool use requests. ```APIDOC ## POST /api/tool_use/handle/default ### Description Default implementation for handling tool use requests. ### Method POST ### Endpoint /api/tool_use/handle/default ### Parameters #### Request Body - **client** (Anthropic) - Required - The Anthropic client instance. - **resp** (Message) - Required - The message containing tool use information. ### Response #### Success Response (200) - **ControlFlow, Vec>** - The control flow for the stop reason or content blocks. #### Response Example ```json { "type": "Stop", "reason": "ToolFinished" } ``` ``` -------------------------------- ### Create Base64ImageSource from File Path Source: https://docs.rs/claudius/0.19.0/claudius/struct.Base64ImageSource.html Creates a Base64ImageSource by reading a file from a given path, encoding its content as base64, and inferring the media type from the file extension. ```rust pub fn from_path>(path: P) -> Result ``` -------------------------------- ### Get Block Count Source: https://docs.rs/claudius/0.19.0/claudius/struct.CitationContentBlockLocation.html Returns the number of content blocks in the citation span. This is a utility method for calculating the length of the cited range. ```rust pub fn block_count(&self) -> i32 ``` -------------------------------- ### Handle Default Tool Use Streaming Source: https://docs.rs/claudius/0.19.0/claudius/trait.Agent.html Default implementation for handling tool use requests with streaming output. Requires a renderer and agent stream context. ```rust fn handle_default_tool_use_streaming<'life0, 'life1, 'life2, 'life3, 'life4, 'async_trait>( &'life0 mut self, client: &'life1 Anthropic, resp: &'life2 Message, renderer: &'life3 mut dyn Renderer, context: &'life4 AgentStreamContext, ) -> Pin, Vec>> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait, 'life4: 'async_trait, ``` -------------------------------- ### Renderer trait implementation: start_tool_use Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.PlainTextRenderer.html Called when a tool use block starts. This method is part of the Renderer trait implementation for PlainTextRenderer. ```rust fn start_tool_use(&mut self, context: &dyn StreamContext, name: &str, id: &str) ``` -------------------------------- ### POST /run Source: https://docs.rs/claudius/0.19.0/claudius/struct.PromptTestConfig.html Executes a prompt test configuration against the Anthropic API and validates assertions. ```APIDOC ## POST /run ### Description Executes the prompt against the Anthropic API and validates all configured assertions. It handles both successful responses and API errors. ### Method POST ### Endpoint /run ### Request Body - **client** (Anthropic) - Required - The Anthropic client instance used to execute the request. ### Response #### Success Response (200) - **result** (PromptTestResult) - The result of the prompt test execution, including success status and response content. ### Errors - Returns an error if neither prompt nor messages are provided. - Returns an error for invalid parameter values (e.g., temperature out of range). - Returns an error for validation failures during request building. ``` -------------------------------- ### unwrap_err() - Get Err value or panic Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Retrieves the contained Err value. Panics if the Result is an Ok, using the Ok's value as the panic message. ```APIDOC ## unwrap_err() ### Description Retrieves the contained `Err` value. Panics if the `Result` is an `Ok`, using the `Ok`'s value as the panic message. ### Method `unwrap_err()` ### Parameters None ### Request Example ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` ### Response #### Success Response (E) - Returns the contained `Err` value. #### Response Example ```rust // If x is Err("emergency failure"), returns "emergency failure" ``` #### Error Handling Panics if the value is an `Ok`. ``` -------------------------------- ### PlainTextRenderer Initialization Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.PlainTextRenderer.html Methods for creating and configuring a new PlainTextRenderer instance. ```APIDOC ## PlainTextRenderer Initialization ### Description Methods to instantiate the renderer with specific color and interrupt settings. ### Methods - **new()**: Creates a new PlainTextRenderer with ANSI colors enabled. - **with_color(use_color: bool)**: Creates a new PlainTextRenderer with specified color setting. - **with_interrupt(interrupted: Arc)**: Attaches an interrupt flag to the renderer. - **with_color_and_interrupt(use_color: bool, interrupted: Arc)**: Creates a new PlainTextRenderer with specified color and interrupt flag. ``` -------------------------------- ### Policy::or Source: https://docs.rs/claudius/0.19.0/claudius/struct.Message.html Creates a new Policy that returns Action::Follow if either the current or the provided policy returns Action::Follow. ```APIDOC ## fn or(self, other: P) -> Or ### Description Create a new `Policy` that returns `Action::Follow` if either `self` or `other` returns `Action::Follow`. ### Parameters #### Path Parameters - **other** (P) - Required - The other policy to evaluate. ``` -------------------------------- ### unwrap_or_default() - Get Ok value or default Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Returns the contained Ok value or a default value if the Result is an Err. Requires the type T to implement the Default trait. ```APIDOC ## unwrap_or_default() ### Description Returns the contained `Ok` value or a default value if the `Result` is an `Err`. Requires the type `T` to implement the `Default` trait. ### Method `unwrap_or_default()` ### Parameters None ### Request Example ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` ### Response #### Success Response (T) - Returns the contained `Ok` value if `Ok`. - Returns the default value for type `T` if `Err`. #### Response Example ```rust // For Ok(1909), returns 1909. // For Err, returns 0 (default for integers). ``` ``` -------------------------------- ### unwrap() - Get Ok value or panic Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Retrieves the contained Ok value. Panics if the Result is an Err, using the Err's value as the panic message. ```APIDOC ## unwrap() ### Description Retrieves the contained `Ok` value. Panics if the `Result` is an `Err`, using the `Err`'s value as the panic message. ### Method `unwrap()` ### Parameters None ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ### Response #### Success Response (T) - Returns the contained `Ok` value. #### Response Example ```rust // If x is Ok(2), returns 2 ``` #### Error Handling Panics if the value is an `Err`. ``` -------------------------------- ### Create and Nest AgentStreamContext Source: https://docs.rs/claudius/0.19.0/claudius/struct.AgentStreamContext.html Demonstrates initializing a root context and creating a child context to increment the nesting depth. ```rust use claudius::AgentStreamContext; let root = AgentStreamContext::root("MainAgent"); assert_eq!(root.depth, 0); let child = root.child("SubAgent"); assert_eq!(child.depth, 1); assert_eq!(child.label, "SubAgent"); ``` -------------------------------- ### SystemPrompt Trait Implementations Source: https://docs.rs/claudius/0.19.0/claudius/enum.SystemPrompt.html Details the trait implementations for SystemPrompt, including Clone, Debug, Deserialize, PartialEq, Serialize, and others. ```APIDOC ## Trait Implementations ### impl Clone for SystemPrompt #### fn clone(&self) -> SystemPrompt Returns a duplicate of the value. #### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. ### impl Debug for SystemPrompt #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. ### impl<'de> Deserialize<'de> for SystemPrompt #### fn deserialize<__D>(__deserializer: __D) -> Result where __D: Deserializer<'de>, Deserialize this value from the given Serde deserializer. ### impl PartialEq for SystemPrompt #### fn eq(&self, other: &SystemPrompt) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. #### fn ne(&self, other: &Rhs) -> bool Tests for `!=`. ### impl Serialize for SystemPrompt #### fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer, Serialize this value into the given Serde serializer. ``` -------------------------------- ### Create New ChatSession with ConfigAgent Source: https://docs.rs/claudius/0.19.0/claudius/chat/struct.ChatSession.html Creates a new chat session using the default ConfigAgent. Requires an Anthropic client and ChatConfig. ```rust pub fn new(client: Anthropic, config: ChatConfig) -> Self ``` -------------------------------- ### Get Thinking Budget Tokens Source: https://docs.rs/claudius/0.19.0/claudius/enum.ThinkingConfig.html Returns the number of budget tokens configured for thinking. Returns 0 if thinking is disabled. Use this to check the current token budget. ```rust pub fn num_tokens(&self) -> u32 ``` -------------------------------- ### expect_err() - Get Err value or panic with custom message Source: https://docs.rs/claudius/0.19.0/claudius/type.Result.html Retrieves the contained Err value. Panics if the Result is an Ok, using a custom panic message provided by the caller. ```APIDOC ## expect_err() ### Description Retrieves the contained `Err` value. Panics if the `Result` is an `Ok`, using a custom panic message provided by the caller, along with the content of the `Ok` value. ### Method `expect_err(msg: &str)` ### Parameters #### Path Parameters - **msg** (string) - Required - The custom panic message. ### Request Example ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` ### Response #### Success Response (E) - Returns the contained `Err` value. #### Response Example ```rust // If x is Err("error message"), returns "error message" ``` #### Error Handling Panics if the value is an `Ok`. ``` -------------------------------- ### Create New Usage Instance Source: https://docs.rs/claudius/0.19.0/claudius/struct.Usage.html Constructs a new `Usage` instance with mandatory input and output token counts. Use this when initializing usage tracking for an API call. ```rust pub fn new(input_tokens: i32, output_tokens: i32) -> Self ```