strands-agents 0.1.0

A Rust implementation of the Strands AI Agents SDK
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
//! Streaming types for model responses.

use serde::{Deserialize, Serialize};

use super::content::Role;

/// Reason why model generation stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    EndTurn,
    ToolUse,
    MaxTokens,
    StopSequence,
    ContentFiltered,
    GuardrailIntervention,
    Interrupt,
}

impl Default for StopReason {
    fn default() -> Self { Self::EndTurn }
}

impl StopReason {
    /// Returns the string representation of the stop reason.
    pub fn as_str(&self) -> &'static str {
        match self {
            StopReason::EndTurn => "end_turn",
            StopReason::ToolUse => "tool_use",
            StopReason::MaxTokens => "max_tokens",
            StopReason::StopSequence => "stop_sequence",
            StopReason::ContentFiltered => "content_filtered",
            StopReason::GuardrailIntervention => "guardrail_intervention",
            StopReason::Interrupt => "interrupt",
        }
    }
}

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

/// Token usage statistics.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Usage {
    pub input_tokens: u32,
    pub output_tokens: u32,
    pub total_tokens: u32,

    #[serde(default)]
    pub cache_read_input_tokens: u32,

    #[serde(default)]
    pub cache_write_input_tokens: u32,
}

impl Usage {
    pub fn new(input_tokens: u32, output_tokens: u32) -> Self {
        Self {
            input_tokens,
            output_tokens,
            total_tokens: input_tokens + output_tokens,
            cache_read_input_tokens: 0,
            cache_write_input_tokens: 0,
        }
    }

    pub fn add(&mut self, other: &Usage) {
        self.input_tokens += other.input_tokens;
        self.output_tokens += other.output_tokens;
        self.total_tokens += other.total_tokens;
        self.cache_read_input_tokens += other.cache_read_input_tokens;
        self.cache_write_input_tokens += other.cache_write_input_tokens;
    }
}

/// Performance metrics for a model call.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Metrics {
    pub latency_ms: u64,

    #[serde(default)]
    pub time_to_first_byte_ms: u64,
}

/// Event indicating message generation has started.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessageStartEvent {
    pub role: Role,
}

/// Tool use information at content block start.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContentBlockStartToolUse {
    pub name: String,
    pub tool_use_id: String,
}

/// Content block start data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ContentBlockStart {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_use: Option<ContentBlockStartToolUse>,
}

/// Event indicating a content block has started.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ContentBlockStartEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_block_index: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<ContentBlockStart>,
}

/// Tool use delta within a content block.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ContentBlockDeltaToolUse {
    pub input: String,
}

/// Reasoning content delta.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ReasoningContentBlockDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub redacted_content: Option<Vec<u8>>,
}

/// Citation delta in streaming response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CitationsDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<serde_json::Value>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_content: Option<Vec<CitationSourceContentDelta>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

/// Source content delta for citations.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CitationSourceContentDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

/// Incremental content block update.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ContentBlockDelta {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_use: Option<ContentBlockDeltaToolUse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub reasoning_content: Option<ReasoningContentBlockDelta>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub citation: Option<CitationsDelta>,
}

/// Event containing a content block delta.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ContentBlockDeltaEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_block_index: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delta: Option<ContentBlockDelta>,
}

/// Event indicating a content block has stopped.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ContentBlockStopEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_block_index: Option<u32>,
}

/// Event indicating message generation has stopped.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct MessageStopEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<StopReason>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_model_response_fields: Option<serde_json::Value>,
}

/// Event containing usage and metrics metadata.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct MetadataEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<Usage>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub metrics: Option<Metrics>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace: Option<serde_json::Value>,
}

/// An exception event from the model.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ExceptionEvent {
    pub message: String,
}

/// A stream error event from the model.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelStreamErrorEvent {
    pub message: String,
    pub original_message: String,
    pub original_status_code: i32,
}

/// Event for content redaction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct RedactContentEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redact_user_content_message: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub redact_assistant_content_message: Option<String>,
}

/// A streaming event from the model.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct StreamEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_start: Option<MessageStartEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_block_start: Option<ContentBlockStartEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_block_delta: Option<ContentBlockDeltaEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_block_stop: Option<ContentBlockStopEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_stop: Option<MessageStopEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<MetadataEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub redact_content: Option<RedactContentEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub internal_server_exception: Option<ExceptionEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_stream_error_exception: Option<ModelStreamErrorEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub throttling_exception: Option<ExceptionEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub validation_exception: Option<ExceptionEvent>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_unavailable_exception: Option<ExceptionEvent>,
}

impl StreamEvent {
    pub fn message_start(role: Role) -> Self {
        Self { message_start: Some(MessageStartEvent { role }), ..Default::default() }
    }

    pub fn content_block_start(index: u32, start: Option<ContentBlockStart>) -> Self {
        Self {
            content_block_start: Some(ContentBlockStartEvent {
                content_block_index: Some(index),
                start,
            }),
            ..Default::default()
        }
    }

    pub fn content_block_delta(index: u32, delta: ContentBlockDelta) -> Self {
        Self {
            content_block_delta: Some(ContentBlockDeltaEvent {
                content_block_index: Some(index),
                delta: Some(delta),
            }),
            ..Default::default()
        }
    }

    pub fn text_delta(index: u32, text: impl Into<String>) -> Self {
        Self::content_block_delta(index, ContentBlockDelta { text: Some(text.into()), ..Default::default() })
    }

    pub fn tool_use_delta(index: u32, input: impl Into<String>) -> Self {
        Self::content_block_delta(index, ContentBlockDelta {
            tool_use: Some(ContentBlockDeltaToolUse { input: input.into() }),
            ..Default::default()
        })
    }

    pub fn tool_use_start(index: u32, name: impl Into<String>, tool_use_id: impl Into<String>) -> Self {
        Self {
            content_block_start: Some(ContentBlockStartEvent {
                content_block_index: Some(index),
                start: Some(ContentBlockStart {
                    tool_use: Some(ContentBlockStartToolUse {
                        name: name.into(),
                        tool_use_id: tool_use_id.into(),
                    }),
                }),
            }),
            ..Default::default()
        }
    }

    pub fn reasoning_delta(index: u32, text: impl Into<String>) -> Self {
        Self::content_block_delta(index, ContentBlockDelta {
            reasoning_content: Some(ReasoningContentBlockDelta {
                text: Some(text.into()),
                ..Default::default()
            }),
            ..Default::default()
        })
    }

    pub fn content_block_stop(index: u32) -> Self {
        Self {
            content_block_stop: Some(ContentBlockStopEvent { content_block_index: Some(index) }),
            ..Default::default()
        }
    }

    pub fn message_stop(stop_reason: StopReason) -> Self {
        Self {
            message_stop: Some(MessageStopEvent { stop_reason: Some(stop_reason), additional_model_response_fields: None }),
            ..Default::default()
        }
    }

    pub fn metadata(usage: Usage, metrics: Metrics) -> Self {
        Self {
            metadata: Some(MetadataEvent { usage: Some(usage), metrics: Some(metrics), trace: None }),
            ..Default::default()
        }
    }

    pub fn is_text_delta(&self) -> bool {
        self.content_block_delta.as_ref().and_then(|e| e.delta.as_ref()).map(|d| d.text.is_some()).unwrap_or(false)
    }

    pub fn as_text_delta(&self) -> Option<&str> {
        self.content_block_delta.as_ref().and_then(|e| e.delta.as_ref()).and_then(|d| d.text.as_deref())
    }

    pub fn is_message_stop(&self) -> bool { self.message_stop.is_some() }
    pub fn stop_reason(&self) -> Option<StopReason> { self.message_stop.as_ref().and_then(|e| e.stop_reason) }

    pub fn is_error(&self) -> bool {
        self.internal_server_exception.is_some()
            || self.model_stream_error_exception.is_some()
            || self.throttling_exception.is_some()
            || self.validation_exception.is_some()
            || self.service_unavailable_exception.is_some()
    }
}

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

    #[test]
    fn test_usage_add() {
        let mut usage1 = Usage::new(100, 50);
        let usage2 = Usage::new(200, 100);
        usage1.add(&usage2);
        assert_eq!(usage1.input_tokens, 300);
        assert_eq!(usage1.output_tokens, 150);
        assert_eq!(usage1.total_tokens, 450);
    }

    #[test]
    fn test_stop_reason_serialization() {
        assert_eq!(serde_json::to_string(&StopReason::EndTurn).unwrap(), "\"end_turn\"");
        assert_eq!(serde_json::to_string(&StopReason::ToolUse).unwrap(), "\"tool_use\"");
    }

    #[test]
    fn test_stream_event_text_delta() {
        let event = StreamEvent::text_delta(0, "Hello");
        assert!(event.is_text_delta());
        assert_eq!(event.as_text_delta(), Some("Hello"));
    }

    #[test]
    fn test_stream_event_serialization() {
        let event = StreamEvent::text_delta(0, "hi");
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("contentBlockDelta"));
    }
}