claude-agent 0.2.25

Rust SDK for building AI agents with Anthropic's Claude - Direct API, no CLI dependency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Provider and model configuration.

use std::collections::{HashMap, HashSet};
use std::env;

use crate::client::messages::{DEFAULT_MAX_TOKENS, MIN_THINKING_BUDGET};

// Anthropic API models
pub const DEFAULT_MODEL: &str = "claude-sonnet-4-5-20250929";
pub const DEFAULT_SMALL_MODEL: &str = "claude-haiku-4-5-20251001";
pub const DEFAULT_REASONING_MODEL: &str = "claude-opus-4-6";
pub const FRONTIER_MODEL: &str = DEFAULT_REASONING_MODEL;

// AWS Bedrock models (using global endpoint prefix for maximum availability)
#[cfg(feature = "aws")]
pub const BEDROCK_MODEL: &str = "global.anthropic.claude-sonnet-4-5-20250929-v1:0";
#[cfg(feature = "aws")]
pub const BEDROCK_SMALL_MODEL: &str = "global.anthropic.claude-haiku-4-5-20251001-v1:0";
#[cfg(feature = "aws")]
pub const BEDROCK_REASONING_MODEL: &str = "global.anthropic.claude-opus-4-6-v1:0";

// GCP Vertex AI models
#[cfg(feature = "gcp")]
pub const VERTEX_MODEL: &str = "claude-sonnet-4-5@20250929";
#[cfg(feature = "gcp")]
pub const VERTEX_SMALL_MODEL: &str = "claude-haiku-4-5@20251001";
#[cfg(feature = "gcp")]
pub const VERTEX_REASONING_MODEL: &str = "claude-opus-4-6";

// Azure Foundry models
#[cfg(feature = "azure")]
pub const FOUNDRY_MODEL: &str = "claude-sonnet-4-5";
#[cfg(feature = "azure")]
pub const FOUNDRY_SMALL_MODEL: &str = "claude-haiku-4-5";
#[cfg(feature = "azure")]
pub const FOUNDRY_REASONING_MODEL: &str = "claude-opus-4-6";

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ModelType {
    #[default]
    Primary,
    Small,
    Reasoning,
}

#[derive(Clone, Debug)]
pub struct ModelConfig {
    pub primary: String,
    pub small: String,
    pub reasoning: Option<String>,
}

impl ModelConfig {
    pub fn new(primary: impl Into<String>, small: impl Into<String>) -> Self {
        Self {
            primary: primary.into(),
            small: small.into(),
            reasoning: None,
        }
    }

    pub fn anthropic() -> Self {
        Self::from_env_with_defaults(DEFAULT_MODEL, DEFAULT_SMALL_MODEL, DEFAULT_REASONING_MODEL)
    }

    fn from_env_with_defaults(
        default_primary: &str,
        default_small: &str,
        default_reasoning: &str,
    ) -> Self {
        Self {
            primary: env::var("ANTHROPIC_MODEL").unwrap_or_else(|_| default_primary.into()),
            small: env::var("ANTHROPIC_SMALL_FAST_MODEL").unwrap_or_else(|_| default_small.into()),
            reasoning: Some(
                env::var("ANTHROPIC_REASONING_MODEL").unwrap_or_else(|_| default_reasoning.into()),
            ),
        }
    }

    #[cfg(feature = "aws")]
    pub fn bedrock() -> Self {
        Self::from_env_with_defaults(BEDROCK_MODEL, BEDROCK_SMALL_MODEL, BEDROCK_REASONING_MODEL)
    }

    #[cfg(feature = "gcp")]
    pub fn vertex() -> Self {
        Self::from_env_with_defaults(VERTEX_MODEL, VERTEX_SMALL_MODEL, VERTEX_REASONING_MODEL)
    }

    #[cfg(feature = "azure")]
    pub fn foundry() -> Self {
        Self::from_env_with_defaults(FOUNDRY_MODEL, FOUNDRY_SMALL_MODEL, FOUNDRY_REASONING_MODEL)
    }

    pub fn primary(mut self, model: impl Into<String>) -> Self {
        self.primary = model.into();
        self
    }

    pub fn small(mut self, model: impl Into<String>) -> Self {
        self.small = model.into();
        self
    }

    pub fn reasoning(mut self, model: impl Into<String>) -> Self {
        self.reasoning = Some(model.into());
        self
    }

    pub fn get(&self, model_type: ModelType) -> &str {
        match model_type {
            ModelType::Primary => &self.primary,
            ModelType::Small => &self.small,
            ModelType::Reasoning => self.reasoning.as_deref().unwrap_or(&self.primary),
        }
    }

    pub fn resolve_alias<'a>(&'a self, alias: &'a str) -> &'a str {
        match alias {
            "sonnet" => &self.primary,
            "haiku" => &self.small,
            "opus" => self.reasoning.as_deref().unwrap_or(&self.primary),
            other => other,
        }
    }
}

impl Default for ModelConfig {
    fn default() -> Self {
        Self::anthropic()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BetaFeature {
    InterleavedThinking,
    ContextManagement,
    StructuredOutputs,
    PromptCaching,
    MaxTokens128k,
    CodeExecution,
    Mcp,
    WebSearch,
    WebFetch,
    OAuth,
    FilesApi,
    Effort,
    /// 1M token context window (for Sonnet 4.5 on Bedrock/Vertex).
    Context1M,
    /// Tool search for progressive disclosure of MCP tools.
    AdvancedToolUse,
}

impl BetaFeature {
    const FEATURES: &'static [(BetaFeature, &'static str)] = &[
        (Self::InterleavedThinking, "interleaved-thinking-2025-05-14"),
        (Self::ContextManagement, "context-management-2025-06-27"),
        (Self::StructuredOutputs, "structured-outputs-2025-11-13"),
        (Self::PromptCaching, "prompt-caching-2024-07-31"),
        (Self::MaxTokens128k, "max-tokens-3-5-sonnet-2024-07-15"),
        (Self::CodeExecution, "code-execution-2025-01-24"),
        (Self::Mcp, "mcp-2025-04-08"),
        (Self::WebSearch, "web-search-2025-03-05"),
        (Self::WebFetch, "web-fetch-2025-09-10"),
        (Self::OAuth, "oauth-2025-04-20"),
        (Self::FilesApi, "files-api-2025-04-14"),
        (Self::Effort, "effort-2025-11-24"),
        (Self::Context1M, "context-1m-2025-08-07"),
        (Self::AdvancedToolUse, "advanced-tool-use-2025-11-20"),
    ];

    pub fn header_value(&self) -> &'static str {
        Self::FEATURES
            .iter()
            .find(|(f, _)| f == self)
            .map(|(_, v)| *v)
            .expect("all variants covered in FEATURES")
    }

    fn from_header(value: &str) -> Option<Self> {
        Self::FEATURES
            .iter()
            .find(|(_, v)| *v == value)
            .map(|(f, _)| *f)
    }

    pub fn all() -> impl Iterator<Item = BetaFeature> {
        Self::FEATURES.iter().map(|(f, _)| *f)
    }
}

#[derive(Clone, Debug, Default)]
pub struct BetaConfig {
    features: HashSet<BetaFeature>,
    custom: Vec<String>,
}

impl BetaConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn all() -> Self {
        Self {
            features: BetaFeature::all().collect(),
            custom: Vec::new(),
        }
    }

    pub fn feature(mut self, feature: BetaFeature) -> Self {
        self.features.insert(feature);
        self
    }

    pub fn custom(mut self, flag: impl Into<String>) -> Self {
        self.custom.push(flag.into());
        self
    }

    pub fn add(&mut self, feature: BetaFeature) {
        self.features.insert(feature);
    }

    pub fn add_custom(&mut self, flag: impl Into<String>) {
        self.custom.push(flag.into());
    }

    pub fn from_env() -> Self {
        let mut config = Self::new();

        if let Ok(flags) = env::var("ANTHROPIC_BETA_FLAGS") {
            for flag in flags.split(',').map(str::trim).filter(|s| !s.is_empty()) {
                if let Some(feature) = BetaFeature::from_header(flag) {
                    config.features.insert(feature);
                } else {
                    config.custom.push(flag.to_string());
                }
            }
        }

        config
    }

    pub fn header_value(&self) -> Option<String> {
        let mut flags: Vec<&str> = self.features.iter().map(|f| f.header_value()).collect();
        flags.sort();

        for custom in &self.custom {
            if !flags.contains(&custom.as_str()) {
                flags.push(custom);
            }
        }

        if flags.is_empty() {
            None
        } else {
            Some(flags.join(","))
        }
    }

    pub fn is_empty(&self) -> bool {
        self.features.is_empty() && self.custom.is_empty()
    }

    pub fn has(&self, feature: BetaFeature) -> bool {
        self.features.contains(&feature)
    }
}

#[derive(Clone, Debug)]
pub struct ProviderConfig {
    pub models: ModelConfig,
    pub max_tokens: u32,
    pub thinking_budget: Option<u32>,
    pub enable_caching: bool,
    pub api_version: String,
    pub beta: BetaConfig,
    pub extra_headers: HashMap<String, String>,
}

impl ProviderConfig {
    pub fn new(models: ModelConfig) -> Self {
        Self {
            models,
            max_tokens: DEFAULT_MAX_TOKENS,
            thinking_budget: None,
            enable_caching: !env::var("DISABLE_PROMPT_CACHING")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false),
            api_version: "2023-06-01".into(),
            beta: BetaConfig::from_env(),
            extra_headers: HashMap::new(),
        }
    }

    pub fn max_tokens(mut self, tokens: u32) -> Self {
        self.max_tokens = tokens;
        if tokens > DEFAULT_MAX_TOKENS {
            self.beta.add(BetaFeature::MaxTokens128k);
        }
        self
    }

    pub fn thinking(mut self, budget: u32) -> Self {
        self.thinking_budget = Some(budget.max(MIN_THINKING_BUDGET));
        self.beta.add(BetaFeature::InterleavedThinking);
        self
    }

    pub fn disable_caching(mut self) -> Self {
        self.enable_caching = false;
        self
    }

    pub fn api_version(mut self, version: impl Into<String>) -> Self {
        self.api_version = version.into();
        self
    }

    pub fn beta(mut self, feature: BetaFeature) -> Self {
        self.beta.add(feature);
        self
    }

    pub fn beta_config(mut self, config: BetaConfig) -> Self {
        self.beta = config;
        self
    }

    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra_headers.insert(key.into(), value.into());
        self
    }

    pub fn requires_128k_beta(&self) -> bool {
        self.max_tokens > DEFAULT_MAX_TOKENS
    }
}

impl Default for ProviderConfig {
    fn default() -> Self {
        Self::new(ModelConfig::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_model_config_get() {
        let config = ModelConfig::anthropic();
        assert!(config.get(ModelType::Primary).contains("sonnet"));
        assert!(config.get(ModelType::Small).contains("haiku"));
        assert!(config.get(ModelType::Reasoning).contains("opus"));
    }

    #[test]
    fn test_provider_config_default_max_tokens() {
        let config = ProviderConfig::default();
        assert_eq!(config.max_tokens, DEFAULT_MAX_TOKENS);
        assert!(!config.requires_128k_beta());
    }

    #[test]
    fn test_provider_config_builder() {
        let config = ProviderConfig::new(ModelConfig::anthropic())
            .max_tokens(16384)
            .thinking(10000)
            .disable_caching();

        assert_eq!(config.max_tokens, 16384);
        assert_eq!(config.thinking_budget, Some(10000));
        assert!(!config.enable_caching);
        assert!(config.requires_128k_beta());
        assert!(config.beta.has(BetaFeature::MaxTokens128k));
        assert!(config.beta.has(BetaFeature::InterleavedThinking));
    }

    #[test]
    fn test_provider_config_auto_128k_beta() {
        let config = ProviderConfig::default().max_tokens(DEFAULT_MAX_TOKENS);
        assert!(!config.beta.has(BetaFeature::MaxTokens128k));

        let config = ProviderConfig::default().max_tokens(DEFAULT_MAX_TOKENS + 1);
        assert!(config.beta.has(BetaFeature::MaxTokens128k));
    }

    #[test]
    fn test_provider_config_thinking_auto_beta() {
        let config = ProviderConfig::default().thinking(5000);
        assert!(config.beta.has(BetaFeature::InterleavedThinking));
        assert_eq!(config.thinking_budget, Some(5000));
    }

    #[test]
    fn test_provider_config_thinking_min_budget() {
        let config = ProviderConfig::default().thinking(500);
        assert_eq!(config.thinking_budget, Some(MIN_THINKING_BUDGET));
    }

    #[test]
    fn test_beta_feature_header() {
        assert_eq!(
            BetaFeature::InterleavedThinking.header_value(),
            "interleaved-thinking-2025-05-14"
        );
        assert_eq!(
            BetaFeature::MaxTokens128k.header_value(),
            "max-tokens-3-5-sonnet-2024-07-15"
        );
    }

    #[test]
    fn test_beta_config_with_features() {
        let config = BetaConfig::new()
            .feature(BetaFeature::InterleavedThinking)
            .feature(BetaFeature::ContextManagement);

        assert!(config.has(BetaFeature::InterleavedThinking));
        assert!(config.has(BetaFeature::ContextManagement));
        assert!(!config.has(BetaFeature::MaxTokens128k));

        let header = config.header_value().unwrap();
        assert!(header.contains("interleaved-thinking"));
        assert!(header.contains("context-management"));
    }

    #[test]
    fn test_beta_config_custom() {
        let config = BetaConfig::new()
            .feature(BetaFeature::InterleavedThinking)
            .custom("new-feature-2026-01-01");

        let header = config.header_value().unwrap();
        assert!(header.contains("interleaved-thinking"));
        assert!(header.contains("new-feature-2026-01-01"));
    }

    #[test]
    fn test_beta_config_all() {
        let config = BetaConfig::all();
        assert!(config.has(BetaFeature::InterleavedThinking));
        assert!(config.has(BetaFeature::ContextManagement));
        assert!(config.has(BetaFeature::MaxTokens128k));
    }

    #[test]
    fn test_provider_config_beta() {
        let config = ProviderConfig::default()
            .beta(BetaFeature::InterleavedThinking)
            .beta_config(
                BetaConfig::new()
                    .feature(BetaFeature::InterleavedThinking)
                    .custom("experimental-feature"),
            );

        assert!(config.beta.has(BetaFeature::InterleavedThinking));
        let header = config.beta.header_value().unwrap();
        assert!(header.contains("experimental-feature"));
    }

    #[test]
    fn test_beta_config_empty() {
        let config = BetaConfig::new();
        assert!(config.is_empty());
        assert!(config.header_value().is_none());
    }

    #[test]
    fn test_provider_config_extra_headers() {
        let config = ProviderConfig::default()
            .header("x-custom", "value")
            .header("x-another", "test");

        assert_eq!(config.extra_headers.get("x-custom"), Some(&"value".into()));
        assert_eq!(config.extra_headers.get("x-another"), Some(&"test".into()));
    }
}