claude-sdk 1.0.0

Native Rust SDK for the Claude API with streaming support and tool execution
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
//! Conversation builder for multi-turn interactions
//!
//! This module provides a builder for managing conversation state,
//! including tool use and multi-turn exchanges.

use crate::types::{
    CacheControl, ContentBlock, Message, MessagesRequest, Role, SystemBlock, SystemPrompt, Tool,
};

/// Builder for managing multi-turn conversations with Claude
///
/// This builder helps manage conversation state, including:
/// - Message history with proper role alternation
/// - Tool definitions
/// - System prompts
/// - Automatic handling of tool use/result cycles
///
/// # Example
///
/// ```rust
/// use claude_sdk::ConversationBuilder;
///
/// let mut conversation = ConversationBuilder::new()
///     .with_system("You are a helpful assistant");
///
/// conversation.add_user_message("Hello!");
///
/// let request = conversation.build("claude-sonnet-4-5-20250929", 1024);
/// ```
#[derive(Debug, Clone)]
pub struct ConversationBuilder {
    messages: Vec<Message>,
    tools: Vec<Tool>,
    system: Option<SystemPrompt>,
}

impl ConversationBuilder {
    /// Create a new conversation builder
    pub fn new() -> Self {
        Self {
            messages: Vec::new(),
            tools: Vec::new(),
            system: None,
        }
    }

    /// Set the system prompt
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::ConversationBuilder;
    ///
    /// let conversation = ConversationBuilder::new()
    ///     .with_system("You are a helpful coding assistant");
    /// ```
    pub fn with_system(mut self, prompt: impl Into<String>) -> Self {
        self.system = Some(SystemPrompt::String(prompt.into()));
        self
    }

    /// Set the system prompt with caching enabled
    ///
    /// This caches the system prompt for ~5 minutes, reducing costs on repeated requests.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::ConversationBuilder;
    ///
    /// let conversation = ConversationBuilder::new()
    ///     .with_cached_system("You are a helpful assistant with access to tools");
    /// ```
    pub fn with_cached_system(mut self, prompt: impl Into<String>) -> Self {
        self.system = Some(SystemPrompt::Blocks(vec![SystemBlock {
            block_type: "text".into(),
            text: prompt.into(),
            cache_control: Some(CacheControl::ephemeral()),
        }]));
        self
    }

    /// Add a tool definition
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{ConversationBuilder, Tool};
    /// use serde_json::json;
    ///
    /// let tool = Tool {
    ///     name: "get_weather".into(),
    ///     description: "Get weather for a location".into(),
    ///     input_schema: json!({
    ///         "type": "object",
    ///         "properties": {
    ///             "location": {"type": "string"}
    ///         },
    ///         "required": ["location"]
    ///     }),
    ///     disable_user_input: Some(true),
    ///     input_examples: None,
    ///     cache_control: None,
    /// };
    ///
    /// let conversation = ConversationBuilder::new()
    ///     .with_tool(tool);
    /// ```
    pub fn with_tool(mut self, tool: Tool) -> Self {
        self.tools.push(tool);
        self
    }

    /// Add multiple tool definitions
    pub fn with_tools(mut self, tools: Vec<Tool>) -> Self {
        self.tools.extend(tools);
        self
    }

    /// Add a tool with caching enabled
    ///
    /// This caches the tool definition, reducing costs when using the same tools repeatedly.
    pub fn with_cached_tool(mut self, mut tool: Tool) -> Self {
        tool.cache_control = Some(CacheControl::ephemeral());
        self.tools.push(tool);
        self
    }

    /// Add a user message
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::ConversationBuilder;
    ///
    /// let mut conversation = ConversationBuilder::new();
    /// conversation.add_user_message("What's the weather in NYC?");
    /// ```
    pub fn add_user_message(&mut self, content: impl Into<String>) -> &mut Self {
        self.messages.push(Message::user(content));
        self
    }

    /// Add an assistant message
    ///
    /// Typically used when reconstructing a conversation from history.
    pub fn add_assistant_message(&mut self, content: impl Into<String>) -> &mut Self {
        self.messages.push(Message::assistant(content));
        self
    }

    /// Add an assistant message with content blocks
    ///
    /// Used when the assistant response includes tool use.
    pub fn add_assistant_with_blocks(&mut self, content: Vec<ContentBlock>) -> &mut Self {
        self.messages.push(Message {
            role: Role::Assistant,
            content,
        });
        self
    }

    /// Add a tool result
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::ConversationBuilder;
    ///
    /// let mut conversation = ConversationBuilder::new();
    /// conversation.add_tool_result("toolu_123", r#"{"temp": 72, "condition": "sunny"}"#);
    /// ```
    pub fn add_tool_result(
        &mut self,
        tool_use_id: impl Into<String>,
        result: impl Into<String>,
    ) -> &mut Self {
        self.messages
            .push(Message::tool_result(tool_use_id, result));
        self
    }

    /// Add a tool result with error flag
    pub fn add_tool_error(
        &mut self,
        tool_use_id: impl Into<String>,
        error_message: impl Into<String>,
    ) -> &mut Self {
        self.messages.push(Message {
            role: Role::User,
            content: vec![ContentBlock::ToolResult {
                tool_use_id: tool_use_id.into(),
                content: Some(error_message.into()),
                is_error: Some(true),
            }],
        });
        self
    }

    /// Get the current message history
    pub fn messages(&self) -> &[Message] {
        &self.messages
    }

    /// Get the tool definitions
    pub fn tools(&self) -> &[Tool] {
        &self.tools
    }

    /// Get the system prompt
    pub fn system(&self) -> Option<&SystemPrompt> {
        self.system.as_ref()
    }

    /// Clear all messages but keep tools and system prompt
    pub fn clear_messages(&mut self) -> &mut Self {
        self.messages.clear();
        self
    }

    /// Build a MessagesRequest from the current conversation state
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::ConversationBuilder;
    ///
    /// let mut conversation = ConversationBuilder::new()
    ///     .with_system("You are helpful");
    ///
    /// conversation.add_user_message("Hello!");
    ///
    /// let request = conversation.build("claude-sonnet-4-5-20250929", 1024);
    /// ```
    pub fn build(&self, model: impl Into<String>, max_tokens: u32) -> MessagesRequest {
        let mut request = MessagesRequest::new(model, max_tokens, self.messages.clone());

        if let Some(system) = &self.system {
            request.system = Some(system.clone());
        }

        if !self.tools.is_empty() {
            request.tools = Some(self.tools.clone());
        }

        request
    }

    /// Build a request and consume the builder
    pub fn into_request(self, model: impl Into<String>, max_tokens: u32) -> MessagesRequest {
        self.build(model, max_tokens)
    }

    /// Estimate the number of tokens in the current conversation
    ///
    /// This includes system prompt, tools, and all messages.
    /// Useful for managing context window limits.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::ConversationBuilder;
    ///
    /// let mut conversation = ConversationBuilder::new()
    ///     .with_system("You are helpful");
    ///
    /// conversation.add_user_message("Hello!");
    ///
    /// let tokens = conversation.estimate_tokens();
    /// println!("Conversation uses ~{} tokens", tokens);
    /// ```
    pub fn estimate_tokens(&self) -> usize {
        let counter = crate::tokens::TokenCounter::new();
        let mut total = 0;

        // System prompt
        if let Some(system) = &self.system {
            total += counter.count_system_prompt(system);
        }

        // Messages
        for message in &self.messages {
            total += counter.count_message(message);
        }

        // Tools
        for tool in &self.tools {
            total += counter.count_tool(tool);
        }

        total
    }

    /// Check if the conversation would fit in a model's context window
    ///
    /// # Example
    ///
    /// ```rust
    /// use claude_sdk::{ConversationBuilder, models};
    ///
    /// let mut conversation = ConversationBuilder::new();
    /// conversation.add_user_message("Hello!");
    ///
    /// let model = &models::CLAUDE_SONNET_4_5;
    /// let fits = conversation.fits_in_context(model, 1024, false);
    /// println!("Fits: {}", fits);
    /// ```
    pub fn fits_in_context(
        &self,
        model: &crate::models::Model,
        max_tokens: u32,
        use_extended_context: bool,
    ) -> bool {
        let counter = crate::tokens::TokenCounter::new();
        let request = self.build(model.anthropic_id, max_tokens);
        counter
            .validate_context_window(&request, model, use_extended_context)
            .is_ok()
    }
}

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

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

    #[test]
    fn test_basic_conversation() {
        let mut conv = ConversationBuilder::new();
        conv.add_user_message("Hello");
        conv.add_assistant_message("Hi there!");
        conv.add_user_message("How are you?");

        assert_eq!(conv.messages().len(), 3);
        assert_eq!(conv.messages()[0].role, Role::User);
        assert_eq!(conv.messages()[1].role, Role::Assistant);
    }

    #[test]
    fn test_with_system() {
        let conv = ConversationBuilder::new().with_system("You are helpful");

        assert!(conv.system().is_some());
        match conv.system().unwrap() {
            SystemPrompt::String(s) => assert_eq!(s, "You are helpful"),
            _ => panic!("Expected String variant"),
        }
    }

    #[test]
    fn test_with_tools() {
        let tool = Tool {
            name: "test_tool".into(),
            description: "A test tool".into(),
            input_schema: json!({"type": "object"}),
            disable_user_input: None,
            input_examples: None,
            cache_control: None,
        };

        let conv = ConversationBuilder::new().with_tool(tool);

        assert_eq!(conv.tools().len(), 1);
        assert_eq!(conv.tools()[0].name, "test_tool");
    }

    #[test]
    fn test_tool_result() {
        let mut conv = ConversationBuilder::new();
        conv.add_tool_result("toolu_123", "success");

        assert_eq!(conv.messages().len(), 1);
        assert_eq!(conv.messages()[0].role, Role::User);

        match &conv.messages()[0].content[0] {
            ContentBlock::ToolResult { tool_use_id, .. } => {
                assert_eq!(tool_use_id, "toolu_123");
            }
            _ => panic!("Expected ToolResult"),
        }
    }

    #[test]
    fn test_build_request() {
        let mut conv = ConversationBuilder::new().with_system("Test system");
        conv.add_user_message("Test message");

        let request = conv.build("claude-sonnet-4-5-20250929", 1024);

        assert_eq!(request.model, "claude-sonnet-4-5-20250929");
        assert_eq!(request.max_tokens, 1024);
        assert_eq!(request.messages.len(), 1);
        assert!(request.system.is_some());
    }

    #[test]
    fn test_clear_messages() {
        let mut conv = ConversationBuilder::new().with_system("System");
        conv.add_user_message("Message 1");
        conv.add_user_message("Message 2");

        assert_eq!(conv.messages().len(), 2);

        conv.clear_messages();
        assert_eq!(conv.messages().len(), 0);
        assert!(conv.system().is_some()); // System preserved
    }

    #[test]
    fn test_cached_system() {
        let conv = ConversationBuilder::new().with_cached_system("Cached prompt");

        match conv.system().unwrap() {
            SystemPrompt::Blocks(blocks) => {
                assert_eq!(blocks.len(), 1);
                assert!(blocks[0].cache_control.is_some());
            }
            _ => panic!("Expected Blocks variant"),
        }
    }
}