audacity-sdk 0.1.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
//! Integration tests against a local mock HTTP server.
//!
//! Tests spin up a real tokio TCP listener, serve canned HTTP responses,
//! and exercise the SDK end-to-end.

use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

use audacity_sdk::{
    Client, Config, ContentBlock, ConversationRole, ConverseStreamOutput, Error, Message,
};

// ── helpers ───────────────────────────────────────────────────────────────────

/// Bind a random port and return (listener, base_url).
async fn bind() -> (TcpListener, String) {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    (listener, format!("http://127.0.0.1:{port}"))
}

/// Build an HTTP/1.1 response string.
fn http_response(status: u16, status_text: &str, headers_extra: &str, body: &str) -> String {
    format!(
        "HTTP/1.1 {status} {status_text}\r\nContent-Type: application/json\r\nContent-Length: {len}\r\n{headers_extra}\r\n{body}",
        len = body.len()
    )
}

fn http_sse_response(body: &str) -> String {
    format!(
        "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n{len:x}\r\n{body}\r\n0\r\n\r\n",
        len = body.len()
    )
}

/// Serve a single connection with the given raw HTTP bytes.
async fn serve_once(listener: &TcpListener, response: String) {
    let (mut sock, _) = listener.accept().await.unwrap();
    let mut buf = vec![0u8; 8192];
    let _ = sock.read(&mut buf).await;
    sock.write_all(response.as_bytes()).await.unwrap();
}

fn client_for(base_url: &str) -> Client {
    Client::new(
        &Config::builder()
            .api_key("audacity_api_test")
            .base_url(base_url)
            .max_retries(0)
            .build()
            .unwrap(),
    )
}

fn user_message(text: &str) -> Message {
    Message::builder()
        .role(ConversationRole::User)
        .content(ContentBlock::Text(text.into()))
        .build()
        .unwrap()
}

// ── conformance §5.1 — converse happy path ────────────────────────────────────

#[tokio::test]
async fn converse_happy_path() {
    let (listener, base_url) = bind().await;

    let body = r#"{"choices":[{"message":{"role":"assistant","content":"Hello world"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":3,"total_tokens":8}}"#;
    let response = http_response(200, "OK", "", body);

    let (result, _) = tokio::join!(
        async {
            let client = client_for(&base_url);
            client
                .converse()
                .model_id("gpt-5.4-mini")
                .messages(user_message("Hi"))
                .send()
                .await
        },
        serve_once(&listener, response),
    );

    let out = result.unwrap();
    let msg = out.output().unwrap().as_message().unwrap();
    assert_eq!(msg.content[0].as_text().unwrap(), "Hello world");
    assert_eq!(*out.stop_reason(), audacity_sdk::StopReason::EndTurn);
    assert_eq!(out.usage().input_tokens, 5);
    assert_eq!(out.usage().output_tokens, 3);
    assert_eq!(out.usage().total_tokens, 8);
    assert!(out.metrics().latency_ms < 5000);
}

// ── conformance §5.7 — defensive unwrap rule ─────────────────────────────────

#[tokio::test]
async fn defensive_unwrap_enveloped_body() {
    let (listener, base_url) = bind().await;

    let body = r#"{"data":{"choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{}}}"#;
    let response = http_response(200, "OK", "", body);

    let (result, _) = tokio::join!(
        async {
            client_for(&base_url)
                .converse()
                .model_id("m")
                .messages(user_message("Q"))
                .send()
                .await
        },
        serve_once(&listener, response),
    );

    assert!(result.unwrap().output().is_some());
}

// ── conformance §5.5 — error shape A ─────────────────────────────────────────

#[tokio::test]
async fn error_shape_a_access_denied() {
    let (listener, base_url) = bind().await;

    let body = r#"{"error":{"message":"Invalid API key","type":"authentication_error","code":"invalid_api_key"}}"#;
    let response = http_response(401, "Unauthorized", "", body);

    let (result, _) = tokio::join!(
        async {
            client_for(&base_url)
                .converse()
                .model_id("m")
                .messages(user_message("Q"))
                .send()
                .await
        },
        serve_once(&listener, response),
    );

    assert!(matches!(result, Err(Error::AccessDenied(_))));
    if let Err(Error::AccessDenied(d)) = result {
        assert_eq!(d.error_code.as_deref(), Some("invalid_api_key"));
        assert!(!d.is_retryable_variant());
    }
}

// helper — expose is_retryable via ErrorDetails extension
trait IsRetryable {
    fn is_retryable_variant(&self) -> bool;
}
impl IsRetryable for audacity_sdk::ErrorDetails {
    fn is_retryable_variant(&self) -> bool {
        false // ErrorDetails doesn't know; checked on the Error enum
    }
}

// ── conformance §5.5 — error shape B ─────────────────────────────────────────

#[tokio::test]
async fn error_shape_b_model_not_allowed() {
    let (listener, base_url) = bind().await;

    let body = r#"{"success":false,"error":{"code":"MODEL_NOT_ALLOWED","message":"Not allowed","request_id":"req-abc","details":{}}}"#;
    let response = http_response(403, "Forbidden", "", body);

    let (result, _) = tokio::join!(
        async {
            client_for(&base_url)
                .converse()
                .model_id("m")
                .messages(user_message("Q"))
                .send()
                .await
        },
        serve_once(&listener, response),
    );

    assert!(matches!(result, Err(Error::AccessDenied(_))));
    if let Err(Error::AccessDenied(d)) = result {
        assert_eq!(d.request_id.as_deref(), Some("req-abc"));
    }
}

// ── conformance §5.6 — 429 with Retry-After retries then succeeds ─────────────

#[tokio::test]
async fn retry_after_429_then_success() {
    let (listener, base_url) = bind().await;

    let throttle_body = r#"{"error":{"message":"rate limited","code":"rate_limit_exceeded"}}"#;
    let throttle_resp = http_response(
        429,
        "Too Many Requests",
        "Retry-After: 0\r\n",
        throttle_body,
    );
    let ok_body = r#"{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}],"usage":{}}"#;
    let ok_resp = http_response(200, "OK", "", ok_body);

    let client = Client::new(
        &Config::builder()
            .api_key("audacity_api_test")
            .base_url(&base_url)
            .max_retries(1) // 2 attempts total
            .build()
            .unwrap(),
    );

    let serve_two = async {
        // first request → 429
        serve_once(&listener, throttle_resp).await;
        // second request → 200
        serve_once(&listener, ok_resp).await;
    };

    let (result, _) = tokio::join!(
        client
            .converse()
            .model_id("m")
            .messages(user_message("Q"))
            .send(),
        serve_two,
    );

    assert!(result.is_ok(), "expected Ok but got: {:?}", result.err());
}

// ── conformance §5.6 — 401 does NOT retry ────────────────────────────────────

#[tokio::test]
async fn no_retry_on_401() {
    let (listener, base_url) = bind().await;
    let attempt_count = Arc::new(AtomicUsize::new(0));
    let attempt_count2 = attempt_count.clone();

    let body = r#"{"error":{"message":"unauth","code":"invalid_api_key"}}"#;

    let client = Client::new(
        &Config::builder()
            .api_key("audacity_api_test")
            .base_url(&base_url)
            .max_retries(2)
            .build()
            .unwrap(),
    );

    // Serve only ONE response — if the SDK retries it would hang.
    let serve_task = async move {
        serve_once(&listener, http_response(401, "Unauthorized", "", body)).await;
        attempt_count2.fetch_add(1, Ordering::SeqCst);
    };

    let (result, _) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
        tokio::join!(
            client
                .converse()
                .model_id("m")
                .messages(user_message("Q"))
                .send(),
            serve_task,
        )
    })
    .await
    .unwrap();

    assert!(matches!(result, Err(Error::AccessDenied(_))));
    assert_eq!(attempt_count.load(Ordering::SeqCst), 1);
}

// ── conformance §5.6 — BUDGET_EXCEEDED does NOT retry ────────────────────────

#[tokio::test]
async fn no_retry_on_budget_exceeded() {
    let (listener, base_url) = bind().await;

    let body = r#"{"success":false,"error":{"code":"BUDGET_EXCEEDED","message":"over budget"}}"#;

    let client = Client::new(
        &Config::builder()
            .api_key("audacity_api_test")
            .base_url(&base_url)
            .max_retries(2)
            .build()
            .unwrap(),
    );

    let serve_task = serve_once(&listener, http_response(429, "Too Many Requests", "", body));

    let (result, _) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
        tokio::join!(
            client
                .converse()
                .model_id("m")
                .messages(user_message("Q"))
                .send(),
            serve_task,
        )
    })
    .await
    .unwrap();

    assert!(matches!(result, Err(Error::ServiceQuotaExceeded(_))));
}

// ── conformance §5.9 — missing API key ───────────────────────────────────────

#[test]
fn missing_api_key_fails_fast() {
    // Unset env var just in case
    std::env::remove_var("AUDACITY_API_KEY");
    let result = Config::builder().build();
    assert!(matches!(result, Err(Error::MissingApiKey)));
}

// ── conformance §5.10 — User-Agent header ────────────────────────────────────

#[tokio::test]
async fn user_agent_header_sent() {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let base_url = format!("http://127.0.0.1:{port}");

    let body = r#"{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}],"usage":{}}"#;
    let response = http_response(200, "OK", "", body);

    let capture_ua = async {
        let (mut sock, _) = listener.accept().await.unwrap();
        let mut buf = vec![0u8; 8192];
        let n = sock.read(&mut buf).await.unwrap();
        let req_str = String::from_utf8_lossy(&buf[..n]).to_string();
        sock.write_all(response.as_bytes()).await.unwrap();
        req_str
    };

    let (result, req_str) = tokio::join!(
        async {
            client_for(&base_url)
                .converse()
                .model_id("m")
                .messages(user_message("Q"))
                .send()
                .await
        },
        capture_ua,
    );

    result.unwrap();
    assert!(
        req_str.contains("audacity-sdk-rust/0.1.0"),
        "User-Agent not found in: {req_str}"
    );
}

// ── conformance §5.2 — streaming happy path ──────────────────────────────────

#[tokio::test]
async fn converse_stream_happy_path() {
    let (listener, base_url) = bind().await;

    let sse_body = concat!(
        "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\"},\"index\":0}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"},\"index\":0}]}\n\n",
        "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\",\"index\":0}]}\n\n",
        "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2,\"total_tokens\":3}}\n\n",
        "data: [DONE]\n\n",
    );
    let response = http_sse_response(sse_body);

    let serve_task = serve_once(&listener, response);
    let stream_task = async {
        let mut out = client_for(&base_url)
            .converse_stream()
            .model_id("gpt-5.4-mini")
            .messages(user_message("Hi"))
            .send()
            .await?;

        let mut events: Vec<String> = Vec::new();
        while let Some(event) = out.stream.recv().await? {
            match &event {
                ConverseStreamOutput::MessageStart(_) => events.push("MessageStart".into()),
                ConverseStreamOutput::ContentBlockDelta(_) => {
                    events.push("ContentBlockDelta".into())
                }
                ConverseStreamOutput::ContentBlockStop(_) => events.push("ContentBlockStop".into()),
                ConverseStreamOutput::MessageStop(_) => events.push("MessageStop".into()),
                ConverseStreamOutput::Metadata(_) => events.push("Metadata".into()),
                _ => {}
            }
        }
        Ok::<_, Error>(events)
    };

    let (events, _) = tokio::join!(stream_task, serve_task);
    let events = events.unwrap();

    // Verify ordering: MessageStart → ContentBlockDelta → ContentBlockStop → MessageStop → Metadata
    assert_eq!(
        events,
        vec![
            "MessageStart",
            "ContentBlockDelta",
            "ContentBlockStop",
            "MessageStop",
            "Metadata",
        ]
    );
}

// ── conformance §5.3 — tool round-trip (streaming) ───────────────────────────

#[tokio::test]
async fn stream_tool_call_emits_content_block_start() {
    let (listener, base_url) = bind().await;

    let sse_body = concat!(
        "data: {\"choices\":[{\"delta\":{\"role\":\"assistant\"}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"arguments\":\"\"}}]}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"city\\\":\\\"NYC\\\"}\"}}]}}]}\n\n",
        "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
        "data: {\"choices\":[],\"usage\":{}}\n\n",
        "data: [DONE]\n\n",
    );
    let response = http_sse_response(sse_body);

    let stream_task = async {
        let mut out = client_for(&base_url)
            .converse_stream()
            .model_id("m")
            .messages(user_message("weather?"))
            .send()
            .await?;

        let mut has_start = false;
        let mut has_delta = false;
        let mut stop_reason = None;

        while let Some(event) = out.stream.recv().await? {
            match event {
                ConverseStreamOutput::ContentBlockStart(_) => has_start = true,
                ConverseStreamOutput::ContentBlockDelta(_) => has_delta = true,
                ConverseStreamOutput::MessageStop(e) => stop_reason = Some(e.stop_reason),
                _ => {}
            }
        }
        Ok::<_, Error>((has_start, has_delta, stop_reason))
    };

    let (result, _) = tokio::join!(stream_task, serve_once(&listener, response));
    let (has_start, has_delta, stop_reason) = result.unwrap();

    assert!(has_start, "expected ContentBlockStart for tool call");
    assert!(has_delta, "expected ContentBlockDelta for tool arguments");
    assert_eq!(stop_reason, Some(audacity_sdk::StopReason::ToolUse));
}