claudius 0.25.0

SDK for the Anthropic API
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
//! Configuration types for the chat application.
//!
//! This module provides CLI argument parsing via `arrrg` and configuration
//! structures for controlling chat behavior.

use std::path::PathBuf;

use arrrg_derive::CommandLine;

use crate::Budget;
use crate::types::{KnownModel, MessageCreateTemplate, Model, SystemPrompt, ThinkingConfig};

/// Default maximum tokens per response.
const DEFAULT_MAX_TOKENS: u32 = 4096;

/// Command-line arguments for the claudius-chat tool.
#[derive(CommandLine, Debug, Default, PartialEq, Eq)]
pub struct ChatArgs {
    /// Model to use for chat.
    #[arrrg(optional, "Model to use (default: claude-haiku-4-5)", "MODEL")]
    pub model: Option<String>,

    /// System prompt to set context for the conversation.
    #[arrrg(optional, "System prompt for the conversation", "PROMPT")]
    pub system: Option<String>,

    /// Maximum tokens per response.
    #[arrrg(optional, "Max tokens per response (default: 4096)", "TOKENS")]
    pub max_tokens: Option<u32>,

    /// Sampling temperature (0.0 to 1.0).
    #[arrrg(optional, "Sampling temperature (0.0 to 1.0)", "TEMP")]
    pub temperature: Option<String>,

    /// Top-p (nucleus) sampling (0.0 to 1.0).
    #[arrrg(optional, "Top-p (nucleus) sampling (0.0 to 1.0)", "TOP_P")]
    pub top_p: Option<String>,

    /// Top-k sampling.
    #[arrrg(optional, "Top-k sampling", "TOP_K")]
    pub top_k: Option<u32>,

    /// Thinking budget (enables extended thinking with given token budget).
    #[arrrg(
        optional,
        "Thinking budget in tokens (enables extended thinking)",
        "TOKENS"
    )]
    pub thinking: Option<u32>,

    /// Disable ANSI colors and styles.
    #[arrrg(flag, "Disable ANSI colors/styles")]
    pub no_color: bool,
}

/// Error type for parsing ChatArgs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatArgsError {
    message: String,
}

impl std::fmt::Display for ChatArgsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for ChatArgsError {}

fn parse_f32_arg(value: &str, name: &str) -> Result<f32, ChatArgsError> {
    value.parse::<f32>().map_err(|_| ChatArgsError {
        message: format!(
            "invalid value for --{}: '{}' is not a valid number",
            name, value
        ),
    })
}

impl TryFrom<ChatArgs> for MessageCreateTemplate {
    type Error = ChatArgsError;

    fn try_from(args: ChatArgs) -> Result<Self, Self::Error> {
        let mut template = MessageCreateTemplate::new();

        if let Some(model) = args.model {
            let parsed = model.parse::<Model>().unwrap_or(Model::Custom(model));
            template = template.with_model(parsed);
        }

        if let Some(system) = args.system {
            template = template.with_system(system);
        }

        if let Some(max_tokens) = args.max_tokens {
            template = template.with_max_tokens(max_tokens);
        }

        if let Some(ref temp) = args.temperature {
            template.temperature = Some(parse_f32_arg(temp, "temperature")?);
        }

        if let Some(ref top_p) = args.top_p {
            template.top_p = Some(parse_f32_arg(top_p, "top-p")?);
        }

        template.top_k = args.top_k;

        if let Some(thinking) = args.thinking {
            template.thinking = Some(ThinkingConfig::enabled(thinking));
        }

        Ok(template)
    }
}

/// Configuration for a chat session.
///
/// This struct holds the resolved configuration values after processing
/// command-line arguments with appropriate defaults.
#[derive(Debug, Clone)]
pub struct ChatConfig {
    /// Template applied to message creation parameters.
    pub template: MessageCreateTemplate,
    /// Whether to use ANSI colors and styles in output.
    pub use_color: bool,
    /// Optional per-session token budget (input + output).
    pub session_budget: Option<Budget>,
    /// Path to persist transcripts automatically after each assistant turn.
    pub transcript_path: Option<PathBuf>,
    /// Whether prompt caching is enabled for this session.
    pub caching_enabled: bool,
}

impl ChatConfig {
    /// Creates a new ChatConfig with default values.
    ///
    /// Defaults:
    /// - Model: claude-haiku-4-5
    /// - Max tokens: 4096
    /// - Color: enabled
    /// - Thinking: disabled
    /// - Caching: enabled
    pub fn new() -> Self {
        Self {
            template: default_template(),
            use_color: true,
            session_budget: None,
            transcript_path: None,
            caching_enabled: true,
        }
    }

    /// Sets the model to use.
    pub fn with_model(mut self, model: Model) -> Self {
        self.template.model = Some(model);
        self
    }

    /// Sets the system prompt.
    pub fn with_system_prompt(mut self, prompt: String) -> Self {
        self.template.system = Some(SystemPrompt::from(prompt));
        self
    }

    /// Sets the maximum tokens per response.
    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
        self.template.max_tokens = Some(max_tokens);
        self
    }

    /// Disables ANSI color output.
    pub fn without_color(mut self) -> Self {
        self.use_color = false;
        self
    }

    /// Sets the sampling temperature.
    pub fn with_temperature(mut self, temperature: Option<f32>) -> Self {
        self.template.temperature = temperature;
        self
    }

    /// Sets the top-p value.
    pub fn with_top_p(mut self, top_p: Option<f32>) -> Self {
        self.template.top_p = top_p;
        self
    }

    /// Sets the top-k value.
    pub fn with_top_k(mut self, top_k: Option<u32>) -> Self {
        self.template.top_k = top_k;
        self
    }

    /// Sets the stop sequences.
    pub fn with_stop_sequences(mut self, stop_sequences: Vec<String>) -> Self {
        self.template.stop_sequences = Some(stop_sequences);
        self
    }

    /// Sets the thinking budget.
    /// `None` disables thinking, `Some(budget)` enables with the given token budget.
    pub fn with_thinking_budget(mut self, budget: Option<u32>) -> Self {
        self.template.thinking = budget.map(ThinkingConfig::enabled);
        self
    }

    /// Sets the session token budget.
    pub fn with_session_budget(mut self, budget: Option<u64>) -> Self {
        self.session_budget = budget.map(Self::token_budget);
        self
    }

    /// Sets the transcript auto-save path.
    pub fn with_transcript_path(mut self, path: Option<PathBuf>) -> Self {
        self.transcript_path = path;
        self
    }

    /// Sets whether prompt caching is enabled.
    pub fn with_caching(mut self, enabled: bool) -> Self {
        self.caching_enabled = enabled;
        self
    }

    /// Returns the configured model.
    pub fn model(&self) -> Model {
        self.template
            .model
            .clone()
            .unwrap_or(Model::Known(KnownModel::ClaudeHaiku45))
    }

    /// Returns the configured max tokens value.
    pub fn max_tokens(&self) -> u32 {
        self.template.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS)
    }

    /// Returns the system prompt as a string, if configured.
    pub fn system_prompt_text(&self) -> Option<&str> {
        match self.template.system.as_ref()? {
            SystemPrompt::String(text) => Some(text.as_str()),
            SystemPrompt::Blocks(_) => None,
        }
    }

    /// Returns the configured stop sequences, if any.
    pub fn stop_sequences(&self) -> &[String] {
        self.template.stop_sequences.as_deref().unwrap_or(&[])
    }

    /// Returns the configured thinking budget, if enabled.
    pub fn thinking_budget(&self) -> Option<u32> {
        match self.template.thinking {
            Some(ThinkingConfig::Enabled { budget_tokens }) => Some(budget_tokens),
            _ => None,
        }
    }

    /// Sets the model.
    pub fn set_model(&mut self, model: Model) {
        self.template.model = Some(model);
    }

    /// Sets or clears the system prompt.
    pub fn set_system_prompt(&mut self, prompt: Option<String>) {
        self.template.system = prompt.map(SystemPrompt::from);
    }

    /// Sets the maximum tokens per response.
    pub fn set_max_tokens(&mut self, max_tokens: u32) {
        self.template.max_tokens = Some(max_tokens);
    }

    /// Sets the sampling temperature.
    pub fn set_temperature(&mut self, temperature: Option<f32>) {
        self.template.temperature = temperature;
    }

    /// Sets the top-p value.
    pub fn set_top_p(&mut self, top_p: Option<f32>) {
        self.template.top_p = top_p;
    }

    /// Sets the top-k value.
    pub fn set_top_k(&mut self, top_k: Option<u32>) {
        self.template.top_k = top_k;
    }

    /// Sets the thinking budget.
    pub fn set_thinking_budget(&mut self, budget: Option<u32>) {
        self.template.thinking = budget.map(ThinkingConfig::enabled);
    }

    /// Sets the session token budget.
    pub fn set_session_budget(&mut self, budget: Option<u64>) {
        self.session_budget = budget.map(Self::token_budget);
    }

    fn token_budget(limit_tokens: u64) -> Budget {
        Budget::new_with_rates(limit_tokens, 1, 1, 1, 1)
    }
}

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

impl TryFrom<ChatArgs> for ChatConfig {
    type Error = ChatArgsError;

    fn try_from(args: ChatArgs) -> Result<Self, Self::Error> {
        let use_color = !args.no_color;
        let template = default_template().merge(MessageCreateTemplate::try_from(args)?);

        Ok(ChatConfig {
            template,
            use_color,
            session_budget: None,
            transcript_path: None,
            caching_enabled: true,
        })
    }
}

fn default_template() -> MessageCreateTemplate {
    let mut template = MessageCreateTemplate::new();
    template.model = Some(Model::Known(KnownModel::ClaudeHaiku45));
    template.max_tokens = Some(DEFAULT_MAX_TOKENS);
    template
}

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

    #[test]
    fn default_config() {
        let config = ChatConfig::new();
        assert_eq!(config.model(), Model::Known(KnownModel::ClaudeHaiku45));
        assert_eq!(config.max_tokens(), 4096);
        assert!(config.use_color);
        assert!(config.template.system.is_none());
        assert!(config.template.temperature.is_none());
        assert!(config.template.top_p.is_none());
        assert!(config.template.top_k.is_none());
        assert!(config.stop_sequences().is_empty());
        assert!(config.thinking_budget().is_none());
        assert!(config.session_budget.is_none());
        assert!(config.transcript_path.is_none());
        assert!(config.caching_enabled);
    }

    #[test]
    fn config_from_args_defaults() {
        let args = ChatArgs::default();
        let config = ChatConfig::try_from(args).unwrap();
        assert_eq!(config.model(), Model::Known(KnownModel::ClaudeHaiku45));
        assert_eq!(config.max_tokens(), 4096);
        assert!(config.use_color);
        assert!(config.thinking_budget().is_none());
    }

    #[test]
    fn config_from_args_custom() {
        let args = ChatArgs {
            model: Some("claude-sonnet-4-0".to_string()),
            system: Some("You are helpful.".to_string()),
            max_tokens: Some(8192),
            temperature: Some("0.7".to_string()),
            top_p: Some("0.9".to_string()),
            top_k: Some(40),
            thinking: Some(2048),
            no_color: true,
        };
        let config = ChatConfig::try_from(args).unwrap();
        assert_eq!(config.model(), Model::Known(KnownModel::ClaudeSonnet40));
        assert_eq!(config.system_prompt_text(), Some("You are helpful."));
        assert_eq!(config.max_tokens(), 8192);
        assert_eq!(config.template.temperature, Some(0.7));
        assert_eq!(config.template.top_p, Some(0.9));
        assert_eq!(config.template.top_k, Some(40));
        assert_eq!(config.thinking_budget(), Some(2048));
        assert!(!config.use_color);
    }

    #[test]
    fn config_from_args_invalid_temperature() {
        let args = ChatArgs {
            temperature: Some("not-a-number".to_string()),
            ..Default::default()
        };
        let result = ChatConfig::try_from(args);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("--temperature"));
        assert!(err.message.contains("not-a-number"));
    }

    #[test]
    fn config_from_args_invalid_top_p() {
        let args = ChatArgs {
            top_p: Some("invalid".to_string()),
            ..Default::default()
        };
        let result = ChatConfig::try_from(args);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("--top-p"));
    }

    #[test]
    fn config_builder_pattern() {
        let config = ChatConfig::new()
            .with_model(Model::Known(KnownModel::ClaudeSonnet40))
            .with_system_prompt("Test prompt".to_string())
            .with_max_tokens(2048)
            .without_color()
            .with_temperature(Some(0.6))
            .with_top_p(Some(0.9))
            .with_top_k(Some(64))
            .with_stop_sequences(vec!["END".to_string()])
            .with_thinking_budget(Some(2048))
            .with_session_budget(Some(10_000))
            .with_transcript_path(Some(PathBuf::from("transcript.json")))
            .with_caching(false);

        assert_eq!(config.model(), Model::Known(KnownModel::ClaudeSonnet40));
        assert_eq!(config.system_prompt_text(), Some("Test prompt"));
        assert_eq!(config.max_tokens(), 2048);
        assert!(!config.use_color);
        assert_eq!(config.template.temperature, Some(0.6));
        assert_eq!(config.template.top_p, Some(0.9));
        assert_eq!(config.template.top_k, Some(64));
        assert_eq!(config.stop_sequences(), vec!["END".to_string()]);
        assert_eq!(config.thinking_budget(), Some(2048));
        assert_eq!(
            config
                .session_budget
                .as_ref()
                .map(Budget::total_micro_cents),
            Some(10_000)
        );
        assert_eq!(
            config.transcript_path,
            Some(PathBuf::from("transcript.json"))
        );
        assert!(!config.caching_enabled);
    }
}