anthropic-sdk-rust 0.1.1

Comprehensive, type-safe Rust SDK for the Anthropic API with streaming, tools, vision, files, and batch processing support
Documentation
use anthropic_sdk::{Anthropic, ClientConfig, MessageCreateBuilder, AuthMethod};
use anthropic_sdk::types::ContentBlock;
use std::time::Duration;

// Helper function to extract text content from response
fn extract_text_from_content(content: &[ContentBlock]) -> String {
    content.iter()
        .filter_map(|block| match block {
            ContentBlock::Text { text } => Some(text.as_str()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join(" ")
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("๐Ÿš€ Dual Authentication Test (Anthropic + eBay Gateway)");
    println!("=====================================================\n");
    
    // Get API key from environment
    let api_key = std::env::var("ANTHROPIC_API_KEY")
        .or_else(|_| std::env::var("EBAY_ANTHROPIC_API_KEY"))
        .unwrap_or_else(|_| {
            println!("โš ๏ธ  No API key found. Using dummy key for configuration test.");
            "test-key".to_string()
        });
    
    // Test 1: Standard Anthropic API authentication
    println!("๐Ÿงช Test 1: Standard Anthropic API (x-api-key header)");
    test_anthropic_auth(&api_key).await?;
    
    // Test 2: eBay Gateway Bearer token authentication
    println!("\n๐Ÿงช Test 2: eBay Gateway (Bearer token)");
    test_ebay_auth(&api_key).await?;
    
    // Test 3: Custom token header (alternative)
    println!("\n๐Ÿงช Test 3: Custom Token Header");
    test_token_auth(&api_key).await?;
    
    println!("\nโœจ Configuration Examples:");
    print_configuration_examples();
    
    Ok(())
}

async fn test_anthropic_auth(api_key: &str) -> Result<(), Box<dyn std::error::Error>> {
    println!("   ๐Ÿ“ก URL: https://api.anthropic.com");
    println!("   ๐Ÿ”‘ Auth: x-api-key header");
    
    let config = ClientConfig::new(api_key)
        .with_auth_method(AuthMethod::Anthropic)
        .with_base_url("https://api.anthropic.com");
    
    let client = Anthropic::with_config(config)?;
    
    let response = client.messages()
        .create(
            MessageCreateBuilder::new("claude-3-5-sonnet-latest", 50)
                .user("Hello from standard Anthropic API!")
                .build()
        )
        .await;
    
    match response {
        Ok(msg) => {
            println!("   โœ… SUCCESS!");
            let text = extract_text_from_content(&msg.content);
            println!("   ๐Ÿ“ Response: {}", text);
        }
        Err(e) => {
            println!("   โŒ Expected failure with dummy key: {}", e);
        }
    }
    
    Ok(())
}

async fn test_ebay_auth(api_key: &str) -> Result<(), Box<dyn std::error::Error>> {
    println!("   ๐Ÿ“ก URL: https://platformgateway2.vip.ebay.com/hubgptgatewaysvc/v1/anthropic");
    println!("   ๐Ÿ”‘ Auth: Authorization: Bearer <token>");
    
    // Method 1: Using with_auth_method
    let config = ClientConfig::new(api_key)
        .with_base_url("https://platformgateway2.vip.ebay.com/hubgptgatewaysvc/v1/anthropic")
        .with_auth_method(AuthMethod::Bearer);
    
    let client = Anthropic::with_config(config)?;
    
    let response = client.messages()
        .create(
            MessageCreateBuilder::new("hubgpt-chat-completions-sonnet-3-7", 50)
                .user("Hello from eBay Gateway!")
                .build()
        )
        .await;
    
    match response {
        Ok(msg) => {
            println!("   โœ… SUCCESS! Bearer token works!");
            let text = extract_text_from_content(&msg.content);
            println!("   ๐Ÿ“ Response: {}", text);
        }
        Err(e) => {
            println!("   โŒ Error: {}", e);
            if api_key == "test-key" {
                println!("   ๐Ÿ’ก This is expected with dummy key. Set real API key to test.");
            }
        }
    }
    
    // Method 2: Using for_ebay_gateway convenience method
    println!("\n   ๐Ÿ”ง Testing convenience method:");
    let ebay_config = ClientConfig::new(api_key)
        .for_ebay_gateway("https://platformgateway2.vip.ebay.com/hubgptgatewaysvc/v1/anthropic");
    
    let ebay_client = Anthropic::with_config(ebay_config)?;
    
    let response2 = ebay_client.messages()
        .create(
            MessageCreateBuilder::new("hubgpt-chat-completions-sonnet-3-7", 50)
                .user("Hello from eBay convenience config!")
                .build()
        )
        .await;
    
    match response2 {
        Ok(msg) => {
            println!("   โœ… Convenience method works!");
            let text = extract_text_from_content(&msg.content);
            println!("   ๐Ÿ“ Response: {}", text);
        }
        Err(e) => {
            println!("   โŒ Error: {}", e);
        }
    }
    
    Ok(())
}

async fn test_token_auth(api_key: &str) -> Result<(), Box<dyn std::error::Error>> {
    println!("   ๐Ÿ“ก URL: Custom gateway with token header");
    println!("   ๐Ÿ”‘ Auth: token header");
    
    let config = ClientConfig::new(api_key)
        .with_base_url("https://platformgateway2.vip.ebay.com/hubgptgatewaysvc/v1/anthropic")
        .with_auth_method(AuthMethod::Token);
    
    let client = Anthropic::with_config(config)?;
    
    let response = client.messages()
        .create(
            MessageCreateBuilder::new("hubgpt-chat-completions-sonnet-3-7", 50)
                .user("Hello with token header!")
                .build()
        )
        .await;
    
    match response {
        Ok(msg) => {
            println!("   โœ… SUCCESS! Token header works!");
            let text = extract_text_from_content(&msg.content);
            println!("   ๐Ÿ“ Response: {}", text);
        }
        Err(e) => {
            println!("   โŒ Error: {}", e);
        }
    }
    
    Ok(())
}

fn print_configuration_examples() {
    println!();
    println!("๐Ÿ“‹ How to Configure for Different Gateways:");
    println!();
    
    println!("๐Ÿ”ธ Standard Anthropic API:");
    println!("```rust");
    println!("let client = Anthropic::new(\"your-api-key\")?;");
    println!("// OR");
    println!("let config = ClientConfig::new(\"your-api-key\")");
    println!("    .with_auth_method(AuthMethod::Anthropic);");
    println!("let client = Anthropic::with_config(config)?;");
    println!("```");
    
    println!("\n๐Ÿ”ธ eBay Gateway (Bearer Token):");
    println!("```rust");
    println!("let config = ClientConfig::new(\"your-api-key\")");
    println!("    .for_ebay_gateway(\"https://platformgateway2.vip.ebay.com/hubgptgatewaysvc/v1/anthropic\");");
    println!("let client = Anthropic::with_config(config)?;");
    println!("// OR manually:");
    println!("let config = ClientConfig::new(\"your-api-key\")");
    println!("    .with_base_url(\"https://platformgateway2.vip.ebay.com/hubgptgatewaysvc/v1/anthropic\")");
    println!("    .with_auth_method(AuthMethod::Bearer);");
    println!("```");
    
    println!("\n๐Ÿ”ธ Custom Token Header:");
    println!("```rust");
    println!("let config = ClientConfig::new(\"your-api-key\")");
    println!("    .with_base_url(\"https://your-gateway.com/api\")");
    println!("    .with_auth_method(AuthMethod::Token);");
    println!("```");
    
    println!("\n๐Ÿ”ธ Environment Variables:");
    println!("```bash");
    println!("export ANTHROPIC_API_KEY='your-key'");
    println!("export ANTHROPIC_BASE_URL='https://platformgateway2.vip.ebay.com/hubgptgatewaysvc/v1/anthropic'");
    println!("export ANTHROPIC_AUTH_METHOD='bearer'  # or 'token' or 'anthropic'");
    println!("```");
    
    println!("\n๐Ÿ’ก The SDK now supports all major authentication patterns!");
}