audacity-sdk 0.2.0

Rust SDK for the Audacity Investments AI gateway — Amazon Bedrock Converse-compatible API surface
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
//! Types mirroring the Amazon Bedrock Converse SDK surface.

use serde::{Deserialize, Serialize};
use serde_json::Value;

// ── Conversation roles ────────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ConversationRole {
    User,
    Assistant,
}

// ── Content blocks ────────────────────────────────────────────────────────────

/// A tool-use invocation block (assistant side).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolUseBlock {
    pub tool_use_id: String,
    pub name: String,
    pub input: Value,
}

/// A single item inside a toolResult content list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolResultContent {
    Text(String),
    Json(Value),
}

/// A tool-result block (user side).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolResultBlock {
    pub tool_use_id: String,
    pub content: Vec<ToolResultContent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
}

/// The format of an image content block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ImageFormat {
    Png,
    Jpeg,
    Gif,
    Webp,
}

impl ImageFormat {
    /// The lowercase wire spelling, also used as the `image/<subtype>` media subtype.
    pub fn as_str(&self) -> &'static str {
        match self {
            ImageFormat::Png => "png",
            ImageFormat::Jpeg => "jpeg",
            ImageFormat::Gif => "gif",
            ImageFormat::Webp => "webp",
        }
    }
}

/// The source of an image content block.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ImageSource {
    /// Raw image bytes (Bedrock parity) — base64-encoded into a data URL on the wire.
    Bytes(Vec<u8>),
    /// An https or data URL, passed through verbatim (Audacity extension).
    Url(String),
}

/// An image block (user side).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageBlock {
    pub format: ImageFormat,
    pub source: ImageSource,
}

/// The kind of prompt-cache breakpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CachePointType {
    #[default]
    Default,
}

/// A prompt-cache breakpoint (Bedrock parity). Placed in message or system
/// content after the prefix to cache: the content part immediately preceding
/// it gets an ephemeral `cache_control` marker on the wire; the block itself
/// is never emitted. A cache point with no preceding content part in the same
/// message is silently ignored.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct CachePointBlock {
    #[serde(rename = "type")]
    pub r#type: CachePointType,
}

impl CachePointBlock {
    /// The standard cache point (`{"type": "default"}`).
    pub fn new() -> Self {
        Self::default()
    }
}

/// A content block that can appear in a message.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ContentBlock {
    Text(String),
    Image(ImageBlock),
    ToolUse(ToolUseBlock),
    ToolResult(ToolResultBlock),
    CachePoint(CachePointBlock),
}

impl ContentBlock {
    /// Returns `Ok(&str)` if this is a `Text` block.
    pub fn as_text(&self) -> Result<&str, &Self> {
        match self {
            ContentBlock::Text(s) => Ok(s.as_str()),
            _ => Err(self),
        }
    }

    /// Returns `Ok(&ImageBlock)` if this is an `Image` block.
    pub fn as_image(&self) -> Result<&ImageBlock, &Self> {
        match self {
            ContentBlock::Image(b) => Ok(b),
            _ => Err(self),
        }
    }

    /// Returns `Ok(&ToolUseBlock)` if this is a `ToolUse` block.
    pub fn as_tool_use(&self) -> Result<&ToolUseBlock, &Self> {
        match self {
            ContentBlock::ToolUse(b) => Ok(b),
            _ => Err(self),
        }
    }

    /// Returns `Ok(&ToolResultBlock)` if this is a `ToolResult` block.
    pub fn as_tool_result(&self) -> Result<&ToolResultBlock, &Self> {
        match self {
            ContentBlock::ToolResult(b) => Ok(b),
            _ => Err(self),
        }
    }

    /// Returns `Ok(&CachePointBlock)` if this is a `CachePoint` block.
    pub fn as_cache_point(&self) -> Result<&CachePointBlock, &Self> {
        match self {
            ContentBlock::CachePoint(b) => Ok(b),
            _ => Err(self),
        }
    }
}

// ── Message ───────────────────────────────────────────────────────────────────

/// A conversation message with a role and one or more content blocks.
#[derive(Debug, Clone)]
pub struct Message {
    pub role: ConversationRole,
    pub content: Vec<ContentBlock>,
}

impl Message {
    pub fn builder() -> MessageBuilder {
        MessageBuilder::default()
    }

    pub fn role(&self) -> &ConversationRole {
        &self.role
    }

    pub fn content(&self) -> &[ContentBlock] {
        &self.content
    }
}

#[derive(Default)]
pub struct MessageBuilder {
    role: Option<ConversationRole>,
    content: Vec<ContentBlock>,
}

impl MessageBuilder {
    pub fn role(mut self, role: ConversationRole) -> Self {
        self.role = Some(role);
        self
    }

    pub fn content(mut self, block: ContentBlock) -> Self {
        self.content.push(block);
        self
    }

    pub fn build(self) -> Result<Message, crate::Error> {
        let role = self
            .role
            .ok_or_else(|| crate::Error::client_validation("Message.role is required"))?;
        if self.content.is_empty() {
            return Err(crate::Error::client_validation(
                "Message must have at least one content block",
            ));
        }
        Ok(Message {
            role,
            content: self.content,
        })
    }
}

// ── System content ─────────────────────────────────────────────────────────────

/// A system-prompt content entry: either text or a prompt-cache breakpoint.
/// Construct with [`SystemContentBlock::text`] or
/// [`SystemContentBlock::cache_point`].
#[derive(Debug, Clone)]
pub struct SystemContentBlock {
    pub text: String,
    /// When `Some`, this entry is a prompt-cache breakpoint (`text` is ignored).
    pub cache_point: Option<CachePointBlock>,
}

impl SystemContentBlock {
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            cache_point: None,
        }
    }

    /// A prompt-cache breakpoint marking the end of the cacheable system prefix.
    pub fn cache_point() -> Self {
        Self {
            text: String::new(),
            cache_point: Some(CachePointBlock::new()),
        }
    }
}

// ── Inference configuration ───────────────────────────────────────────────────

#[derive(Debug, Clone, Default)]
pub struct InferenceConfiguration {
    pub max_tokens: Option<u32>,
    pub temperature: Option<f64>,
    pub top_p: Option<f64>,
    pub stop_sequences: Option<Vec<String>>,
}

impl InferenceConfiguration {
    pub fn builder() -> InferenceConfigurationBuilder {
        InferenceConfigurationBuilder::default()
    }
}

#[derive(Default)]
pub struct InferenceConfigurationBuilder {
    inner: InferenceConfiguration,
}

impl InferenceConfigurationBuilder {
    pub fn max_tokens(mut self, v: u32) -> Self {
        self.inner.max_tokens = Some(v);
        self
    }
    pub fn temperature(mut self, v: f64) -> Self {
        self.inner.temperature = Some(v);
        self
    }
    pub fn top_p(mut self, v: f64) -> Self {
        self.inner.top_p = Some(v);
        self
    }
    pub fn stop_sequences(mut self, v: Vec<String>) -> Self {
        self.inner.stop_sequences = Some(v);
        self
    }
    pub fn build(self) -> InferenceConfiguration {
        self.inner
    }
}

// ── Tool configuration ────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct ToolInputSchema {
    pub json: Value,
}

#[derive(Debug, Clone)]
pub struct ToolSpecification {
    pub name: String,
    pub description: Option<String>,
    pub input_schema: ToolInputSchema,
}

#[derive(Debug, Clone)]
pub struct Tool {
    pub tool_spec: ToolSpecification,
}

#[derive(Debug, Clone)]
pub enum ToolChoice {
    Auto,
    Any,
    Tool { name: String },
}

#[derive(Debug, Clone)]
pub struct ToolConfiguration {
    pub tools: Vec<Tool>,
    pub tool_choice: Option<ToolChoice>,
}

// ── Converse output ───────────────────────────────────────────────────────────

/// Output wrapper — mirrors Bedrock's `ConverseOutput` enum.
#[derive(Debug, Clone)]
pub enum ConverseOutputEnum {
    Message(Message),
}

impl ConverseOutputEnum {
    /// Returns `Ok(&Message)` if this is the `Message` variant.
    pub fn as_message(&self) -> Result<&Message, &Self> {
        match self {
            ConverseOutputEnum::Message(m) => Ok(m),
            // future variants would fall through here
        }
    }
}

#[derive(Debug, Clone)]
pub struct TokenUsage {
    pub input_tokens: u32,
    pub output_tokens: u32,
    pub total_tokens: u32,
    /// Prompt tokens served from the provider's prompt cache (Bedrock name).
    pub cache_read_input_tokens: u32,
    /// Prompt tokens written to the provider's prompt cache (Bedrock name).
    pub cache_write_input_tokens: u32,
}

#[derive(Debug, Clone)]
pub struct Metrics {
    pub latency_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StopReason {
    EndTurn,
    MaxTokens,
    ToolUse,
    StopSequence,
    ContentFiltered,
}

impl StopReason {
    pub(crate) fn from_finish_reason(s: &str) -> Self {
        match s {
            "stop" => StopReason::EndTurn,
            "length" => StopReason::MaxTokens,
            "tool_calls" | "function_call" => StopReason::ToolUse,
            "content_filter" => StopReason::ContentFiltered,
            _ => StopReason::EndTurn,
        }
    }
}

/// The top-level response from a `converse()` call.
#[derive(Debug)]
pub struct ConverseOutput {
    pub(crate) output: Option<ConverseOutputEnum>,
    pub(crate) stop_reason: StopReason,
    pub(crate) usage: TokenUsage,
    pub(crate) metrics: Metrics,
}

impl ConverseOutput {
    pub fn output(&self) -> Option<&ConverseOutputEnum> {
        self.output.as_ref()
    }
    pub fn stop_reason(&self) -> &StopReason {
        &self.stop_reason
    }
    pub fn usage(&self) -> &TokenUsage {
        &self.usage
    }
    pub fn metrics(&self) -> &Metrics {
        &self.metrics
    }
}

// ── Stream event types ────────────────────────────────────────────────────────

#[derive(Debug, Clone)]
pub struct MessageStartEvent {
    pub role: ConversationRole,
}

#[derive(Debug, Clone)]
pub struct ContentBlockStartToolUse {
    pub tool_use_id: String,
    pub name: String,
}

#[derive(Debug, Clone)]
pub enum ContentBlockStartPayload {
    ToolUse(ContentBlockStartToolUse),
}

#[derive(Debug, Clone)]
pub struct ContentBlockStartEvent {
    pub content_block_index: u32,
    pub start: ContentBlockStartPayload,
}

#[derive(Debug, Clone)]
pub enum ContentBlockDeltaPayload {
    Text(String),
    ToolUse { input: String },
}

#[derive(Debug, Clone)]
pub struct ContentBlockDeltaEvent {
    pub content_block_index: u32,
    pub delta: ContentBlockDeltaPayload,
}

#[derive(Debug, Clone)]
pub struct ContentBlockStopEvent {
    pub content_block_index: u32,
}

#[derive(Debug, Clone)]
pub struct MessageStopEvent {
    pub stop_reason: StopReason,
}

#[derive(Debug, Clone)]
pub struct MetadataEvent {
    pub usage: TokenUsage,
    pub metrics: Metrics,
}

/// All possible stream events — one variant per Bedrock stream event type.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ConverseStreamOutput {
    MessageStart(MessageStartEvent),
    ContentBlockStart(ContentBlockStartEvent),
    ContentBlockDelta(ContentBlockDeltaEvent),
    ContentBlockStop(ContentBlockStopEvent),
    MessageStop(MessageStopEvent),
    Metadata(MetadataEvent),
}